2 ms·
This is an interesting idea. The core of it seems to be that the most efficient way to write locks today is to spin for a bit on contention, then yield to the k
by saagarjha 3y ago
This is an interesting idea. The core of it seems to be that the most efficient way to write locks today is to spin for a bit on contention, then yield to the kernel if you've been waiting to long. The goal, of course, is that if the lock is quickly released you don't take the full cost of a kernel call and can just keep going in userspace. Darwin's os_unfair_lock (and the closely related WebKit WTF::Lock) both use this strategy.
Interestingly, XNU already has an implementation of this that is somewhat similar in spirit: preemption free zones (https://github.com/search?q=repo%3Aapple-oss-distributions%2Fxnu%20pfz&type=code https://github.com/search?q=repo%3Aapple-oss-distributions%2...). As far as I can tell os_atomic_lock does not use it for this purpose. Instead, it exists to allow OSAtomicFifoEnqueue/OSAtomicFifoDequeue to be lock-free, and in the typical Apple fashion solves the problem of "what if a userspace application uses this for evil" by implementing it in the kernel and mapping it via the commpage (think vDSO), so there isn't really any room for anyone but Apple to put code there.
Apple being Apple, they could have absolutely added PFZ to os_atomic_lock (for themselves, of course). One wonders why they didn't; perhaps it just turns out that it isn't worth the complexity.
(Look, I'm sorry all I talk about is Apple stuff, that's all I know.)
- spacechild1 3y ago> The core of it seems to be that the most efficient way to write locks today is to spin for a bit on contention, then yield to the kernel if you've been waiting to long. This is an old idea and many real-world mutex implementation have been doing this since forever. Some even let you configure the spin count: https://learn.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-initializecriticalsectionandspincount https://learn.microsoft.com/en-us/windows/win32/api/synchapi...
- saagarjha 3y agoYeah this is nothing new, I'm just saying that Linux is looking to service this better.
- spacechild1 3y agoAlright, I was just tripping over the word "today", since this has already been true 20 years ago :)