7

单个位的 spinlock 实现 folly::PicoSpinLock

 3 years ago
source link: https://zhiqiang.org/coding/folly-picospinlock.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

单个位的 spinlock 实现 folly::PicoSpinLock

作者: 张志强

, 发表于 2020-01-05

, 共 882 字 , 共阅读 119 次

之前提到单字节且为 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.

avatar-0.jpg

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK