之前提到单字节且为 POD 结构的自旋锁实现folly::MicroSpinLock
,而folly:PicoSpinLock
则只需要一个位!实现代码在https://github.com/facebook/folly/blob/master/folly/synchronization/PicoSpinLock.h。
其实现更需要 CPU 底层指令的支持。具体不多说。想说的一个有意思的地方在于,实现文件的最前面提出:
N.B. You most likely do not want to use PicoSpinLock or any other kind of spinlock. Consider MicroLock instead.
In short, spinlocks in preemptive multi-tasking operating systems have serious problems and fast mutexes like std::mutex are almost certainly the better choice, because letting the OS scheduler put a thread to sleep is better for system responsiveness and throughput than wasting a timeslice repeatedly querying a lock held by a thread that's blocked, and you can't prevent userspace programs blocking.
Spinlocks in an operating system kernel make much more sense than they do in userspace.
这里说的应该跟内核里使用自旋锁会关闭中断有关。在用户态里使用自旋锁,无法关闭中断的情况下,一旦被中断切走,自旋锁就真的在空空干等了。
Q. E. D.