Something I’ve been missing in Rust from some other languages is AtomicReferences, basically lock-free thread-safe (mutable) data containers.
This could be done as a safe wrapper around AtomicPtr. Such a safe wrapper would work much like Cell<T>, but with heap-allocated T, powered by AtomicPtr.
For your average type there would be the basics “new”, “set”, “replace”, “swap”, similar to standard Cell<T>. The main difference is that AtomicCell<T> would be Send + Sync, which makes it usable in Arc<T>.
You might’ve noticed there would be no “get”. That’s because the following could happen:
- Thread A retrieves pointer atomically.
- Thread B swaps pointer atomically.
- Thread B frees old pointer. (!)
- Thread A reads (now freed) pointer. (!)
This would be most likely to happen as a result of “acell.replace(x)”, which allocates space for the replacement, swaps the pointers, copies the old value onto the stack, drops the old pointer, and returns. (I don’t know how to solve this.)
This provides a very basic safe wrapper around AtomicPtr. So basic that it can’t even compare and swap! What’s the point of going lock-free if you can’t benefit from it? Well… the idea is that it would have compare and swap, I just haven’t figured this out yet.
It would be really nice to have that compare and swap functionality, and it’s the main reason why I want something like this. But I’m having a hard time figuring it out.