I don't know about you, but for the longest time I had a hard time remembering why we need to wrap types like Mutex
, RwLock
or Atomic*
in an Arc
.
I just had a neat idea for how to "visualize" what Rc
and Arc
are. Maybe it can help others that struggle with it as well.
Basically it boils down to
Arc<T>
~ &T
Let's elaborate with Mutex
as an example. The idea of a Mutex<R>
is that we can share it through a reference &Mutex<R>
across threads because it uses interior mutability and synchronization mechanisms to make sure we don't get data races. The problem with a reference like &Mutex<R>
is that in general we cannot send it freely between threads. You usually get livetime problems unless you can use a thread::scope
.
Now imagine Arc<T>
as a fancier version of a reference &T
. It basically is a reference that circumvents lifetime problems by owning the reffered-to value. We create the first one with Arc::new()
and every further one with Arc::clone()
. So using Arc
there is now no problem sending Arc<Mutex<P>>
between threads.
Of course, this is not really something new. But this image
Arc<T>
~ &T
has somehow been missing from my brain.