Find Related products on Amazon

Shop on Amazon

Fun with Futex

Published on: 2025-06-13 21:37:25

Fun with Futex Implementing an optimized lock in Linux requires some Operating System help. You can only get so far by doing everything in user-land. We are going to take a look how one can implement a simple spin lock in C (just like the spin lock in Go I implemented a while back) and then a slightly more elaborate lock using operating system’s primitives. The idea behind a mutex (mutual exclusion) is straightforward: we want some part of the code to be accessed only by a single thread at a time. If the resource a thread is trying to access (the critical zone) is already being accessed by something else: wait. The trick about implementing them is how you to do wait part! As usual, for the ones allergic to rambling, you can jump directly to the final code on GitHub. Behold the spin lock! The simplest way to wait in a mutex to “spin”. in other words: retry until your condition is met. Here’s a first pass implementation of our mutex in C: typedef struct { atomic_bool locked; } spin_ ... Read full article.