SPSC lock-free queue
In Chapter 5, we implemented an SPSC lock-free queue as an example of how to synchronize access to a data structure from two threads without using locks. This queue is accessed by just two threads: one producer pushing data to the queue and one consumer popping data from the queue. It’s the easiest queue to synchronize.
We used two atomic variables to represent the head (buffer index to read) and tail (buffer index to write) of the queue:
std::atomic<std::size_t> head_ { 0 }; std::atomic<std::size_t> tail_ { 0 };
To avoid false sharing, we can change the code to the following:
alignas(64) std::atomic<std::size_t> head_ { 0 }; alignas(64) std::atomic<std::size_t> tail_ { 0 };
After this change, we can run the code we implemented to measure the number of operations per second (push/pop) performed by the producer and consumer threads. The code can be found in this book’s GitHub repository.
Now, we can run perf
...