Is lock-free concurrency on non-primitive data types possible via `AtomicPtr`?


So what the code does is use an AtomicPtr that points to the heap where the data is stored, and multiple threads mutate the data via the AtomicPtr.

Thought that the mutation of the data is within one atomic operation, so race shouldn't happen. What did I miss?

If I misused AtomicPtr, then what is the practical use? Any examples? Thanks.

Edit: To add on, I'm trying to build a tree-like data structure where the nodes are atomic. Knowing that Mutex and Convar would do the job, but I was being naive in trying something stupid. This is how I learn. :sweat_smile:

AtomicPtr doesn't (and can't) make mutation behind the pointer atomic. The only thing it does is allow you to manipulate the pointer itself atomically.


Is there any use case? The offhand I can imagine is using AtomicPtr reading (only) multiple memory concurrently.

Is it possible to achieve lock-free concurrency on non-primitives other than spin locks?

You might be looking for Atomic. In theory there is no guarantee that this type is in fact lock free; in practice it should be lock free for any struct whose size is no larger than the largest atomic primitive on your platform.

1 Like

For an example, RCU needs atomic pointer updates.

1 Like

Stumbled upon this crate and looked inside the code before. Correct me if I'm wrong, but it falls back to a spinlock if the type isn't primitive. That's a bit of a bummer.

Thanks for the info!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.