I was experimenting with a new multi layered algorithm to draw many layers of a screen at once. Obviously you would need some for of synchronization mechanism, and thus i found myself looking for a traditional Edgar Dijkstra Semaphore.
Now there is a catch, since in Cocoa you will need to lock and unlock in the same thread, in both threads. This seams like a contradiction since we want to convey a message between the threads (basically the worker threads want to say: “he i’m done”.
NSConditionLock, makes this straightforward, whereas it is not possible with plain NSLocks. For example, to block the background thread:
[condLock lockWhenCondition: 1]; // block until 1 (eg wait for data to settle)
[condLock unlock];
In the main thread:
[condLock lock];
[condLock unlockWithCondition:1]; // 1 means background thread can
proceed
assuming that the lock was created/initialized with -initWithCondition:
0.
Now a similar scheme can be used to have the main thread wait for all the worker threads to end. You can even use the same NSConditionLock for it.
Leave a Reply