Spinning around: Please don't – Common problems with spin locks

DIY spin locks spark a meltdown: pros yell 'stop', rebels say 'it just works'

TLDR: A veteran dev warns that DIY spin locks—code that endlessly waits—are a bad idea and shows how they break. Comments erupt: experts say use OS tools like futexes, skeptics question if this ever works, and contrarians claim the “dumb” approach is reliable. It’s a cautionary tale with memes.

An exasperated engineer dropped a spicy blog warning: stop rolling your own spin locks, the kind of code that makes a thread loop until a resource frees up. He even shows a “broken” version where two threads both think they grabbed the lock—cue horror music. The fix involves atomic operations (single, all-or-nothing updates), but the author’s big message is louder: don’t build this yourself; use your operating system’s tools. He name‑checks fairness, speed, and priority inversion (when a low‑priority task blocks a high‑priority one) as bear traps. The vibe? If you touch spin locks without deep expertise, you will get burned.

Commenters lit up. jcranmer laid down the rule: “don’t, unless you have very good reason,” pointing to futexes (fast OS-assisted waits) as the sane base. jeffbee wanted a bigger spotlight on unfairness, warning about starvation—some threads can be left waiting forever. CamperBob2 sighed, wondering if this stuff ever truly works. Then a-dub swaggered in with the contrarian take: spin locks are the dumb duct tape that “just works.” gafferongames cheered. Meme watch: folks joked it’s like giving your code a fidget spinner; others riffed on the author’s “atomic” line with nuclear meltdown gags. Verdict: cautionary tale meets hot‑takes bonfire.

Key Points

  • A simple check-then-set spin lock implementation can allow multiple threads to acquire the lock simultaneously, causing race conditions.
  • Using non-atomic shared flags can lead to tearing and unsafe behavior on some CPU architectures.
  • Replacing a non-atomic flag with std::atomic and using atomic exchange can ensure exclusive lock acquisition by checking the previous value.
  • Atomic operations prevent observation of intermediate states on the targeted memory, reducing race conditions for those operations.
  • The article advises using OS synchronization primitives instead of custom spin locks due to pitfalls like fairness, priority inversion, and NUMA-related issues.

Hottest takes

"don't, unless you have very good reason not to." — jcranmer
"extraordinary and, hypothetically, unbounded" — jeffbee
"the dumb inefficient thing... but actually just works" — a-dub
Made with <3 by @siedrix and @shesho from CDMX. Powered by Forge&Hive.