Shared read-only variable with string value with Arc
- We can use Arc to create Reference Counting around the data.
- The clone on the Arc will only increment the reference counter, but does not copy the data.
examples/threads/shared-read-only-variable-string-with-arc/src/main.rs
use std::sync::Arc; use std::time::Duration; fn main() { let answer = Arc::new(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! 0x7fffeddb81b0 0x61db86afeb80 Started: Hello World! 0x7fffeddb81b0 0x61db86afeb80 ThreadId(2) Hello World! 0x78f1c1bffa78 0x61db86afeb80 ThreadId(3) Hello World! 0x78f1c17ffa78 0x61db86afeb80 ThreadId(4) Hello World! 0x78f1c13ffa78 0x61db86afeb80 After: Hello World! 0x7fffeddb81b0 0x61db86afeb80