A spin_mutex is semantically equivalent to a regular mutex, except for the following:
- A spin_mutex is just 1 byte, whereas a regular mutex is quite large (44 bytes for pthread).
- A spin_mutex is extremely fast to lock and unlock, whereas a regular mutex is surprisingly expensive just to acquire a lock.
- A spin_mutex takes CPU while it waits, so this can be very wasteful compared to a regular mutex that blocks (gives up its CPU slices until it acquires the lock).
The bottom line is that mutex is the usual choice, but in cases where you need to acquire locks very frequently, but only need to hold the lock for a very short period of time, you may save runtime by using a spin_mutex, even though it's non-blocking.
N.B. A spin_mutex is only the size of a bool. To avoid "false
sharing", be careful not to put two spin_mutex objects on the same cache line (within 128 bytes of each other), or the two mutexes may effectively (and wastefully) lock against each other.
Definition at line 177 of file thread.h.