On Dec 7, 2011, at 12:07 PM, Jean-Daniel Dupas wrote: > > Le 7 déc. 2011 à 06:10, Ken Thomases a écrit : > >> On Dec 6, 2011, at 10:05 PM, Don Quixote de la Mancha wrote: >> >> You still shouldn't implement it manually using atomic increment and >> decrement. You should use OSSpinLock if that's what you're attempting. >> Which was my point. The original code was horrible and horribly misguided >> (and suffers from a race condition as others have pointed out, which is >> virtually inevitable when people try to reimplement synchronization instead >> of using ready-made synchronization primitives). >> > > A better solution would be to use posix mutex and completely avoid OSSpinLock. > There is really few situations where SpinLock give you any benefit, as mutex > implementation already try to spin a couple of time before locking. So if > there is no contention, they are both very cheap and fast, and if there is > contention, the mutex is better as it don't consume CPU waiting for other > threads. > > -- Jean-Daniel
A possibly even better solution is to use dispatch semaphores. A non-recursive mutex can be build upon a semaphore. A pthread mutex always requires a call through the kernel. Dispatch semaphores require this only when the thread needs to be blocked. Otherwise, a spin lock is performed in user space. In the case of no contention, a dispatch semaphore is much faster than a pthread mutex. In case of contention, performance is comparable - but extreme contention should be avoided and considered a programmer error. I've successfully used dispatch semaphores and variants to implement a mutex to synchronize access to resources. Well, and even yet another solution is to use dispatch queues, if possible. dispatch lib is open source and available on other platforms, too. But this would require to change the design. Andreas _______________________________________________ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com