Get the latest tech news
Fun with Futex
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!
The problem with this implementation is that your CPU consumption will be pretty high, specially if you spun up as many threads as available cores (can be noticed by room temperature going up). The main thing that this approach from the paper will do different, is to avoid this extra kernel space context switch, and only call wake if we believe that there is a thread waiting. A good way to exemplify that, would be adding an operation in the critical zone that requires a little more than a single CPU instruction and therefore would make threads hold onto the lock for a while longer.
Or read this on Hacker News