Hacker News new | ask | show | jobs
by jstapels 3478 days ago
I honestly don't see how any of these implementations are better than simply using a bool to track whether the queue is empty or not (as suggested in one of the comments on the original article). You could even use the highest bit of the write index to store the bool value if memory was an issue.
3 comments

Some of these implementations also reduce the number of branches, which is generally a good performance idea in modern pipelined, branch-predicting CPUs, but not possible in all cases or even a guaranteed win for performance.

FWIW I checked what I did with the last ring buffer I wrote: I used position + length to eke out that last cell. As the original article notes, it's not a concurrency-friendly solution, but I wasn't writing for that in this case.

One possible reason is that storing a bool separately from the index makes it difficult to update the producer or consumer index atomically. With the implementations that store the full producer and consumer states as a single word each, only single-word atomic operations are necessary to build a lock-free ring. Storing the bool as the high bit of the index would also suffice.
Another approach gives each element a 'data ready' flag (ie the real element type inherits from T). This flag is set by a producer and cleared by the consumer. This would give you an empty/full indication.