NSSemaphore … missing?

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.

Advertisements
Tagged with: , , ,
Posted in Code

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories
%d bloggers like this: