News for hackers. Stuff that matters.
Re:I've been writing ring buffers wrong all these years by heisenbit on Wednesday December 14, 2016 @11:32AM (#13177244)
As far as I can tell that int wrap around could be avoided by

- subtracting buffer size from both pointers once the read pointer has wrapped.

- choosing a longer int for the math operation where possible

That seems a small price for the freedom to be able to choose an appropriate buffer size.

Re:I've been writing ring buffers wrong all these years by mark-r on Wednesday December 14, 2016 @01:40PM (#13178473)
One of the benefits of the original algorithm is the independence of the read and write indexes, they can be updated from different threads (or different processors!) without any atomic operations beyond writing or reading a value. Subtracting from both pointers requires an additional atomic read/modify/write operation.
Re:I've been writing ring buffers wrong all these years by Guvante on Wednesday December 14, 2016 @03:00PM (#13179153)
You could also just restrict the pointers in the normal way but to two times the size of the buffer. So instead of wrapping at N you wrap at 2*N.

You are only encoding 1 bit of data (first or second) so adding more data than that by allowing unsigned integer overflow is just an optimization, not fundamentally necessary.

Re:I've been writing ring buffers wrong all these years by mark-r on Wednesday December 14, 2016 @03:31PM (#13179382)
If you do that then the size() function becomes a problem. The original implementation relies on unsigned integer wrap-around to give the proper result when write < read.
Re:I've been writing ring buffers wrong all these years by caf on Wednesday December 14, 2016 @06:55PM (#13180936)
That is fairly easy to fix, though. Add N to the size value you get until its non-negative.
Re:I've been writing ring buffers wrong all these years by amag on Wednesday December 14, 2016 @04:48PM (#13179973)
It all depends on your use case. In my experience, most of the times when dealing with RB:s, it's more important to guarantee that the read index and the write index can be updated lock-free by different threads (e.g. one producer and one consumer) than to have a very specific non-power-of-2 capacity.