Sharing data between threads

There is one special reference-counted pointer that can be shared between threads that we already mentioned: std::sync::Arc. The main difference from the Rc is that the Arc counts the references with an atomic counter. This means that the kernel will make sure that all updates to the reference count will happen one by one, making it thread-safe. Let's see it with an example:

use std::thread;use std::sync::Arc;fn main() {    let my_vec = vec![10, 33, 54];    let pointer = Arc::new(my_vec);    let t_pointer = pointer.clone();    let handle = thread::Builder::new()        .name("my thread".to_owned())        .spawn(move || {            println!("Vector in second thread: {:?}", t_pointer);        })        .expect("could not create the thread"); println!("Vector in ...

Get Rust High Performance now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.