Hasty Briefsbeta

Bilingual

Writing mutexes from scratch in Go

4 months ago
  • #mutex
  • #concurrency
  • #go
  • Mutexes (mutual exclusion locks) ensure only one thread can execute a critical section of code at a time.
  • A naive spin lock implementation using a boolean variable fails due to race conditions.
  • Atomic operations (e.g., `atomic.SwapUint32`) fix race conditions by ensuring read-modify-write operations are indivisible.
  • Spin locks can be optimized by yielding CPU time (`runtime.Gosched()`) to reduce busy-waiting overhead.
  • Futexes (fast userspace mutexes) leverage OS system calls (`FUTEX_WAIT`, `FUTEX_WAKE`) to park threads instead of busy-waiting.
  • An improved futex lock tracks lock state (0=unlocked, 1=locked no waiters, 2=locked with waiters) to minimize unnecessary wake-ups.
  • Adaptive spinning (brief busy-waiting before sleeping) balances performance in high-contention scenarios.
  • Benchmarks show futex-based locks reduce CPU usage but may lag in raw speed compared to spin locks under low contention.
  • Open questions include fairness guarantees, cross-platform futex alternatives, and dynamic lock behavior tuning.