linux' "mutex lock" 是使用 "memory barrier" 实现的吗?
Is linux' "mutex lock" implemented using "memory barrier"?
我正在阅读 this where Robert Love mentioned that mutex is implemented using memory barrier but I am not able to see the memory barrier instructions being used in Linux implementation 互斥锁。
我想知道他是否指的是 posix 库中的互斥锁实现,该库确实使用了内存屏障指令,因此它不会针对关键资源进行重新排序。我说得对吗?
Robert Love 的回答适用于任何区域的互斥锁。
您引用的 linux 内核中的实现使用 __mutex_fastpath_lock
,它完成大部分工作并且通常使用汇编代码实现。例如,在 x86_64 上,它的 implementation 可能是:
20 static inline void __mutex_fastpath_lock(atomic_t *v,
21 void (*fail_fn)(atomic_t *))
22 {
23 asm_volatile_goto(LOCK_PREFIX " decl %0\n"
24 " jns %l[exit]\n"
25 : : "m" (v->counter)
26 : "memory", "cc"
27 : exit);
28 fail_fn(v);
29 exit:
30 return;
31 }
这里的关键是dec
(decl
)操作前的LOCK前缀(LOCK_PREFIX)。在 x86 上,LOCK 前缀表示 原子性 并且始终 表示完整的内存屏障 .
确实,互斥量需要一些内存同步。重要的是如何在没有繁忙的自旋锁的情况下等待互斥体被解锁(由其他线程)(特别是因为您不希望等待线程吃掉很多CPU)。了解 futex(7). Like clone(2), the futex(2) 系统调用仅对线程库的 实现者 有用。
顺便说一句,POSIX 个线程的 GNU libc & musl-libc are free software 个实现。所以研究他们的源代码如果你想了解细节。
我正在阅读 this where Robert Love mentioned that mutex is implemented using memory barrier but I am not able to see the memory barrier instructions being used in Linux implementation 互斥锁。
我想知道他是否指的是 posix 库中的互斥锁实现,该库确实使用了内存屏障指令,因此它不会针对关键资源进行重新排序。我说得对吗?
Robert Love 的回答适用于任何区域的互斥锁。
您引用的 linux 内核中的实现使用 __mutex_fastpath_lock
,它完成大部分工作并且通常使用汇编代码实现。例如,在 x86_64 上,它的 implementation 可能是:
20 static inline void __mutex_fastpath_lock(atomic_t *v,
21 void (*fail_fn)(atomic_t *))
22 {
23 asm_volatile_goto(LOCK_PREFIX " decl %0\n"
24 " jns %l[exit]\n"
25 : : "m" (v->counter)
26 : "memory", "cc"
27 : exit);
28 fail_fn(v);
29 exit:
30 return;
31 }
这里的关键是dec
(decl
)操作前的LOCK前缀(LOCK_PREFIX)。在 x86 上,LOCK 前缀表示 原子性 并且始终 表示完整的内存屏障 .
确实,互斥量需要一些内存同步。重要的是如何在没有繁忙的自旋锁的情况下等待互斥体被解锁(由其他线程)(特别是因为您不希望等待线程吃掉很多CPU)。了解 futex(7). Like clone(2), the futex(2) 系统调用仅对线程库的 实现者 有用。
顺便说一句,POSIX 个线程的 GNU libc & musl-libc are free software 个实现。所以研究他们的源代码如果你想了解细节。