A fundamental building block of parallelism in Rust is the Arc, which stands for Atomically Reference Counted. Functionally, it works the same way as an Rc, which we have looked at in Chapter 5, Advanced Data Structures; Sharing ownership with smart pointers. The only difference is that the reference counting is done using atomic primitives, which are versions of primitive data types like usize that have well-defined parallel interactions. This has two consequences:
- An Arc is slightly slower than an Rc, as the reference counting involves a bit more work
- An Arc can be used safely across threads
The constructor of Arc looks the same as Rc[7]:
let some_resource = Arc::new("Hello World".to_string());
This creates an Arc over a String. A String is a struct that is not inherently saved to be manipulated across threads. In Rust terms, we say that String is not Sync (more about that later in the recipe Atomically access primitives).
Now let's look at how a thread...