I was reading 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 of mutex lock.
I was wondering if he was referring to mutex lock implementation in posix library which does use memory barrier instruction so that it doesn't get reordered with respect to the critical resource. Am I right?
That Robert Love's answer is applicable to mutexes in any area.
Implementation in the linux kernel you refers uses __mutex_fastpath_lock
, which do most the work and usually implementing using assembler code. E.g., on x86_64 its implementation could be:
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 }
The key here is LOCK prefix (LOCK_PREFIX) before dec
(decl
) operation. On x86 LOCK prefix means atomicity and always implies full memory barrier.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With