Can I share immutable data among threads?
use std::thread::spawn;
fn main() {
let shared = String::from("cake");
let tasks = vec![1, 2, 3];
let mut threads = Vec::new();
for task in tasks {
threads.push(spawn(|| {
println!("This is task {} and we are sharing one single {}", task, shared);
}));
}
for t in threads {
t.join().unwrap();
}
}
error[E0373]: closure may outlive the current function, but it borrows `task`, which is owned by the current function
--> src/main.rs:12:28
|
12 | threads.push(spawn(|| {
| ^^ may outlive borrowed value `task`
13 | println!("This is task {} and we are sharing one single {}", task, shared);
| ---- `task` is borrowed here
|
note: function requires argument type to outlive `'static`
But if I add move
then the closure gobbles up shared
:
error[E0382]: use of moved value: `shared`
--> src/main.rs:12:28
|
5 | let shared = String::from("cake");
| ------ move occurs because `shared` has type `std::string::String`, which does not implement the `Copy` trait
...
12 | threads.push(spawn(move || {
| ^^^^^^^ value moved into closure here, in previous iteration of loop
13 | println!("This is task {} and we are sharing one single {}", task, shared);
| ------ use occurs due to use in closure