Jacob Vosmaer's blog

Ruby mutexes

2019-12-05

Ruby's Mutex class is implemented in thread_sync.c. (Ruby 2.6)

The implementation does not look thread safe. Mutex#try_lock does a straight C assignment. Mutex#lock is a lot more complex because it has to block and sleep in case the mutex is already locked. This releases the GVL via native_sleep.

I guess Mutex doesn't have to be thread-safe because it's running under the GVL. There is no risk of concurrent updates.

If all the critical segments under a mutex never release the GVL, do you even need the mutex? No one can touch the thing the mutex is protecting. You could say it only makes sense to use a mutex if you can end up releasing the GVL in the critical segment. It's hard to guarantee that won't happen, so better use a mutex and don't think about it.

If you're in the special case where the mutex is not strictly needed, meaning, it's impossible for a thread to release the GVL while holding the mutex, then you should end up on a efficient happy path and the cost of locking/unlock the mutex is small. (?)

Tags: ruby

IndexContact