4 ms·
That's my understanding too. In Linux mutexes are implemented by futexes (Fast User-Space mutexes). If there is no contention they are guaranteed to not perform
by m4nu3l 3y ago
That's my understanding too. In Linux mutexes are implemented by futexes (Fast User-Space mutexes). If there is no contention they are guaranteed to not perform a syscall https://en.wikipedia.org/wiki/Futex https://en.wikipedia.org/wiki/Futex
- cout 3y agoMaybe this has changed, but last time I looked at futexes there was no syscall for locking (assuming no contention), but unlocking always made a syscall. This was many years ago so it could be different now.
- m4nu3l 3y agoThe code isn't the easiest to read but in glibc it seems that the syscall is only performed if waiters are detected in userspace during an unlock operation https://github.com/lattera/glibc/blob/master/nptl/pthread_mutex_unlock.c#LL161C2-L161C16 https://github.com/lattera/glibc/blob/master/nptl/pthread_mu...
- gpderetta 3y agoIndeed You only need to FUTEX_WAKE if you know there are waiters (or of you lost track of the number of waiters).
- m4nu3l 3y agoWhat can cause the mutex to lose track of the number of waiters?
- ot 3y agoGenerally you have a small number of bits to count the waiters, because the mutex state has to be a word you can CAS and so you have either 32 or 64 bits to pack all the state you need. If your counter saturates you lose track of the waiters, and you have to fallback somehow.
- m4nu3l 3y agoMakes sense, thanks for the explanation!
- tialaramex 3y agoAlthough it's not the code C++ will be using the Rust implementation is a bit easier to follow: https://doc.rust-lang.org/src/std/sys/unix/locks/futex_mutex.rs.html https://doc.rust-lang.org/src/std/sys/unix/locks/futex_mutex... Unlock is just:: self.futex.swap(0, Release) -- if the value we get back is 2 then we know at least one thread is asleep waiting on this futex, so we need a system call to wake them, but in the uncontended case we're done immediately.