Created
June 6, 2025 20:10
-
-
Save sundeepgupta/02f13efdfad5af488fcefacfc780d66e to your computer and use it in GitHub Desktop.
Thread-safe testing multiple threads entering a function at the same time in Swift with XCTest
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
final class Fixme { | |
private var value: NSObject? | |
private let lock = NSLock() | |
func perform() -> NSObject { | |
lock.lock() | |
defer { lock.unlock() } | |
if let value { return value } | |
let v = NSObject() | |
value = v | |
return v | |
} | |
} | |
final class FixmeTests: XCTestCase { | |
func testRaceConditionInPerform() { | |
let fixme = Fixme() | |
let queue = DispatchQueue(label: #function, attributes: .concurrent) | |
let group = DispatchGroup() | |
let threadCount = 10 | |
let semaphore = DispatchSemaphore(value: 0) | |
var results = Array<NSObject?>(repeating: nil, count: threadCount) | |
for i in 0..<threadCount { | |
group.enter() | |
queue.async { | |
semaphore.wait() // Line up this individual thread onto the starting line | |
results[i] = fixme.perform() | |
group.leave() | |
} | |
} | |
// Starts the race | |
for _ in 0..<threadCount { | |
semaphore.signal() | |
} | |
group.wait() | |
let first = results[0]! | |
for result in results { | |
XCTAssert(first === result!) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment