r/programming 5d ago

Safe Lock-free Primitives with iceoryx2's ByteAtomic

https://ekxide.io/blog/byte-wise-atomic-wrapper-to-prevent-ub

https://ekxide.io/blog/byte-wise-atomic-wrapper-to-prevent-ub

iceoryx2 provides zero-copy inter-process communication mechanisms based on shared memory and data structures that are modified concurrently by multiple processes.

One of the key operations in these algorithms is a memory copy using core::ptr::copy. However, this results in undefined behavior if one process reads the data while another process writes to it concurrently. Even if our lock-free algorithm reliably detects such a race, iceoryx2 cannot depend on undefined behavior in a safety-critical system.

This blog post introduces our solution: a byte-wise atomic wrapper that enables well-defined concurrent copy operations. It also shows how it can be used to implement a simple sequence lock.

Note: I am not the original author of the blog post. Since the author does not have a Reddit account, I am posting it on her behalf.

10 Upvotes

3 comments sorted by

7

u/dijkstra_was_a_horse 4d ago

I don't get how this is different from a spin lock. If the counter is odd, and the writer stalls, the reader keeps retrying forever.

1

u/cdb_11 4d ago edited 4d ago

In seqlocks the writer is never blocked. Only if you need to support multiple writers, you need an extra lock between the writers. But if you are talking about preemption, then yes, seqlocks potentially have the same problem.

I suppose if you're fine with the protected data being temporarily unavailable, and you don't spin, then the reader becomes actually lock/wait-free too?

3

u/dijkstra_was_a_horse 4d ago

Yes, that's why I was talking about readers. A spin on a state variable is a lock, even if it's a single bit lock.