Sharing resources in multithreaded closures
It's time to look at parallelism at a lower level, without any crates to help us. We will now check out how to share a resource across threads so that they all can work with the same object. This recipe will also serve as a refresher on manually creating threads, in case it's been a while since you learned about it.
How to do it...
In the folder
bin
, create a file calledsharing_in_closures.rs
.Add the following code and run it with
cargo run --bin sharing_in_closures
:
1 use std::thread; 2 use std::sync::Arc; 3 4 fn main() { 5 // An Arc ("Atomically Reference Counted") is used the exact 6 // same way as an Rc, but also works in a parallel context 7 let some_resource = Arc::new("Hello World".to_string()); 8 9 // We use it to give a new thread ownership of a clone of the Arc 10 let thread_a = { 11 // It is very common to give the clone the same name as the original 12 let some_resource = some_resource.clone...