SPSCQueue Done Right
From a locked queue, step by step, to a lock-free single-producer single-consumer queue: all the two threads really have to share is two indices. Give each its own cacheline and it’s twenty times faster than locking.
- Compared with a simple mutex-based implementation, an efficient lock-free implementation can be 20x faster.
- The empty/full check really just needs to know the queue size. And the size can be computed directly from the indices.
- The read index and the write index are each written by only one thread, so it’s best to lay them out in two separate cachelines, so that the two threads never write the same cacheline.