Running two threads in a strict interleaved order

Your setup describes two threads performing cooperative multitasking. When multiple threads have to communicate with each other, a condition lock might be the best synchronization idiom:

let lock = NSConditionLock(condition: 1)

Thread {
    while true {
        lock.lock(whenCondition: 1)
        print("first")
        lock.unlock(withCondition: 2)
    }
}.start()

Thread {
    while true {
        lock.lock(whenCondition: 2)
        print("second")
        lock.unlock(withCondition: 1)
    }
}.start()
4 Likes