I am learning concurrency and want to clarify my understanding on the following code example from the Rust book. Please correct me if I am wrong.
use std::
std::sync::Arc is a smart pointer, one that adds the following abilities:
An atomically reference counted wrapper for shared state.
Arc
(and its non-thread-safe friend std::rc::Rc) allow shared ownership. That means that multiple "handles" point to the same value. Whenever a handle is cloned, a reference counter is incremented. Whenever a handle is dropped, the counter is decremented. When the counter goes to zero, the value that the handles were pointing to is freed.
Note that this smart pointer does not call the underlying clone
method of the data; in fact, there may doesn't need to be an underlying clone
method! Arc
handles what happens when clone
is called.
What is the new "owned handle"? It sounds like a reference to the data?
It both is and isn't a reference. In the broader programming and English sense of the word "reference", it is a reference. In the specific sense of a Rust reference (&Foo
), it is not a reference. Confusing, right?
The second part of your question is about std::sync::Mutex, which is described as:
A mutual exclusion primitive useful for protecting shared data
Mutexes are common tools in multithreaded programs, and are well-described
elsewhere so I won't bother repeating that here. The important thing to note is that a Rust Mutex
only gives you the ability to modify shared state. It is up to the Arc
to allow multiple owners to have access to the Mutex
to even attempt to modify the state.
This is a bit more granular than other languages, but allows for these pieces to be reused in novel ways.