Shared read-only variable with string value
- The string must be cloned for this to work.
examples/threads/shared-read-only-variable-string/src/main.rs
use std::time::Duration; fn main() { let answer = String::from("Hello World!"); println!("Before: {answer} {:p} {:?}", &answer, answer.as_ptr()); let mut handles = vec![]; for _ in 1..=3 { let answer = answer.clone(); handles.push(std::thread::spawn(move || { println!( "{:?} {} {:p} {:?}", std::thread::current().id(), answer, &answer, answer.as_ptr() ); std::thread::sleep(Duration::from_millis(10)); })); } println!("Started: {answer} {:p} {:?}", &answer, answer.as_ptr()); for handle in handles { handle.join().unwrap(); } println!("After: {answer} {:p} {:?}", &answer, answer.as_ptr()); }
Before: Hello World! 0x7fffa8e341c8 0x5c8f8538db80 Started: Hello World! 0x7fffa8e341c8 0x5c8f8538db80 ThreadId(2) Hello World! 0x7d60e73ffb70 0x5c8f8538dba0 ThreadId(4) Hello World! 0x7d60e6bffb70 0x5c8f8538e090 ThreadId(3) Hello World! 0x7d60e6fffb70 0x5c8f8538de50 After: Hello World! 0x7fffa8e341c8 0x5c8f8538db80