Wednesday, December 16, 2015 [Tweets] [Favorites]

OSSpinLock Is Unsafe

John McCall (via Peter Steinberger):

Spin locks are, unfortunately, illegal on iOS, which does not guarantee progress in the face of priority inversion.

Greg Parker:

OSSpinLock is unsafe unless you can guarantee that all users have the same priority.

David Smith:

also applies to the new MacBooks since they will depress priority and throttle in thermal overload situations.

to compensate, pthread mutexes are 2-2.5x faster than they used to be on new OSs

It’s a shame that this is not documented. But how great is it to see Apple engineers discuss these sorts of details in public?

Update (2015-12-31): Kevin Ballard:

The reason for this comes back to the thread scheduler and QOS. You remember how I said low-priority threads will eventually execute? That’s no longer true with QOS. More specifically, threads in a higher QOS class will never decay to a lower QOS class, and the scheduler will always prioritize runnable threads in a given QOS class before threads in lower classes. And since threads spinning on a spinlock are always runnable, this means that if there’s enough high-QOS threads waiting on a lock held by a lower-QOS thread, the thread that owns the lock will never execute.

[…]

The Obj-C runtime switched to a handoff lock algorithm, where the spinlock is the size of a word and the owning thread actually stores its thread ID in the lock. Threads that block on the lock can then temporarily donate their priority to the thread that owns the lock, which fixes the priority inversion. There’s potential issues when multiple locks are involved, but in practice it works. The only problem with this solution is it relies on private API, and the spinlock implementation itself isn’t public, so there’s no way for third-party code to use these locks.

3 Comments

[…] OSSpinLock 外,dispatch_semaphore 和 pthread_mutex 性能是最高的。有消息称,苹果在新系统中已经优化了 pthread_mutex 的性能,所以它看上去和 […]

[…] OSSpinLock Is Unsafe, Mutexes and Closure Capture in […]

Stay up-to-date by subscribing to the Comments RSS Feed for this post.

Leave a Comment