Sharing data across multiple threads in rust

Hello everyone,

I've been exploring methods to share data among multiple threads in Rust, specifically within the same process. During my research, I came across the Arc (Atomic Reference Counting) mechanism, which keeps track of the number of owners a particular variable has.

I wanted to clarify the internal implementation of Arc and understand how it accomplishes this reference counting. Does it rely on operating system APIs for locking mechanisms such as mutex, or does it utilize atomic operations?

Please feel free to correct any misconceptions in my understanding.

Atomic operations.

If you need exclusive access (for example to create a &mut to the shared value), you need an Arc<Mutex<_>> or similar.

1 Like

Well, Atomic Reference Counting pointers are using atomic operations (hence the name). Arc just keeps track of instances via AtomicUsize strong and weak counters:

Thank you very much, @quinedot and @jofas, for confirming. I have one more question. Since I need to share a mutable reference of a variable, I understand that I need to combine Arc with another atomic operation from the atomic module. However, I noticed that most of the atomic operations in the atomic module are available for primitive types. So, my question is, how can I share a mutable reference of a struct variable across multiple threads while avoiding the use of OS-based synchronization mechanisms like Mutex?

I think you can use third party crates which provide mutexes that don't use OS-based synchronization. Maybe parking_lot.

Alternatively, I think it's possible to use unsafe and AtomicPtr to make your own mutex or similar synchronization primitive (which might, for example, simply atomically swap a reference instead of providing exclusive access to the pointee).

If you just need "exclusive access" for initialization, you might like to take a look at LazyLock (unstable yet) or the once_cell crate, which, for example, provides a OnceBox (that entirely avoids locking).

A web search showed up the atomicbox crate (I have never used it), which might be an alternative if you want to entirely replace a value at a later time.

But generally, the solution to your problem seems to be parking_lot or some sort of mutex which is implemeneted without using the OS.

1 Like

Thank you for the suggestions. I will explore these crates.

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.