r/cpp • • Mar 24 '26

Optimizing a Lock-Free Ring Buffer

https://david.alvarezrosa.com/posts/optimizing-a-lock-free-ring-buffer/
106 Upvotes

58 comments sorted by

View all comments

Show parent comment

1

u/david-alvarez-rosa Mar 24 '26

Sorry, don't fully understand the benefit here, or how that's different

2

u/Deaod Mar 24 '26

The benefit is only there when dealing with unknown element sizes, ie. one element takes 8 bytes, the next 24, etc.. This allows you to not have any holes in your buffer that the consumer has to jump over.

This is not relevant for queues that deal with elements of known-at-compile-time sizes.

1

u/david-alvarez-rosa Mar 24 '26

The example forces the type. It would be interesting to see how it could be generalized, but not a big fan of heterogeneous containers tbh

2

u/SirClueless Mar 25 '26

If the data is inherently heterogeneous, it's the least-bad option. For example if the items in the queue are network packets.

2

u/RogerV Mar 25 '26

in DPDK all the ring buffers just hold pointers to packets - the packets are in an mbuf pool. makes it possible to clone a ref count on a packet - say, into a pcap ring buffer.

3

u/[deleted] Mar 24 '26

[removed] — view removed comment

1

u/david-alvarez-rosa Mar 24 '26

Oh I see. That's quite specific, not sure which is your usecase

1

u/ack_error Mar 25 '26

I don't see why memcpy() would be a problem, since that's in userspace. No fault would occur since there would be a valid address mapping, it just happens to alias the same physical memory or backing storage as 64KB back in virtual address space.

System calls are more interesting as the kernel would be accessing the memory. I suspect it'd also be fine, but there are less guarantees in that case.

1

u/rzhxd Mar 24 '26

That just simplifies reading the data from the buffer and writing the data into it.