Writing mutexes from scratch in Go

13 points by tholok


mknyszek

The blog post is a nice primer on locks but is missing some important details about sync.Mutex (not necessarily the fault of the author, who does ask some additional questions at the bottom of the post).

Calling into the Linux futex syscalls directly will block the entire thread (forcing a full OS-level context switch by either creating a new thread or reusing an existing one to run other Go code), not just the goroutine. This is much worse than sync.Mutex, where the underlying thread can be reused for some other goroutine. That's a major difference between sync.Mutex and what's implemented here.

What's implemented here is closer in spirit to runtime.mutex (used only in the Go runtime) which has the same downsides, but is in many circumstances (like in the scheduler itself) the only choice.

(sync.Mutex has also accumulated other useful behaviors over the years thanks to feedback from production systems, like falling back to a fair queuing mode under heavy contention to sidestep total performance collapse under heavy contention.)