Have you ever thought of a situation in which two threads need to communicate between each other? Let’s suppose one is a producer thread which produces data which will be used by a consumer thread. The obvious method to tackle this issue is to keep a common buffer right between them where the producer dumps its data into the buffer and the consumer reads the same. The one and only over head involved is that of, when the write operation is done the buffer will be locked by the producer thread. So the consumer thread has to wait until the buffer is released before it starts reading. This approach is fine until situation become some thing like the number of transactions between the threads goes around few thousands/sec. In fact situations like that occurs very frequently in game servers which require thousands of requested to be handled on per second basis. In such demanding situations the performance seem to come down drastically just because the consumer thread is put on hold when ever a write operation is on.
One good solution for this problem is the Ring buffer. The idea is simple and classy. They use 2 pointers one for read and one for write. Using write pointer the data is written into the buffer while the read pointer reads the written data. When the read pointer and write pointer points to the same location, the buffer is empty. One important condition that needs to be checked out is that of the read pointer overtake write pointer, you know what happens
The concept of Spin buffers is a direct extension of the Ring buffer. Spin buffers contains three internal “ordered” buffers. The buffers are ordered as 0, 1, and 2. Two pointers are maintained — one that points to a buffer that a reader reads from, and another one that writes. At any time there can be an assigned read buffer (R), an assigned write buffer (w), and free one (f). The buffers can be implemented as fixed-sized arrays.
Now lets take a look at how write method is implemented:
- Put the item into the write buffer.
- If the next buffer is free, make the free buffer become the write buffer, and the current write buffer becomes free.
It’s just the vice-versa with read method:
-
Read the item from the read buffer.
-
If the current read buffer is empty and the next buffer is free, make the next buffer the read buffer, and the current read buffer becomes free.
But you might be thinking where is that big advantage that you where hyping about. Look closely and you will notice the whole idea doesn’t involve any level of synchronization between the read and write methods. This means there is no dependency on each other and no one waits for the other. No locks means no wait means lots of time saved.





