Last active
July 17, 2024 21:52
-
-
Save tjpalmer/315958ba1715eb7b03cf25e7f23d96e8 to your computer and use it in GitHub Desktop.
Arc Mutex as self
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::sync::{Arc, RwLock}; | |
use std::thread; | |
#[derive(Debug, Default)] | |
struct SharedDataStruct { | |
value: i32, | |
} | |
#[derive(Clone, Debug, Default)] | |
struct SharedData(Arc<RwLock<SharedDataStruct>>); | |
impl SharedData { | |
fn new(value: i32) -> Self { | |
Self(Arc::new(RwLock::new(SharedDataStruct { value }))) | |
} | |
fn value(self: &Self) -> i32 { | |
self.0.read().unwrap().value | |
} | |
fn set_value(self: &Self, new_value: i32) { | |
self.0.write().unwrap().value = new_value; | |
} | |
} | |
fn main() { | |
let shared_data = SharedData::new(42); | |
let handles: Vec<_> = (0..10).map(|i| { | |
let shared_data = shared_data.clone(); | |
thread::spawn(move || { | |
shared_data.set_value(i); | |
println!("Thread {}: {}", i, shared_data.value()); | |
}) | |
}).collect(); | |
for handle in handles { | |
handle.join().unwrap(); | |
} | |
println!("Final value: {}", shared_data.value()); | |
println!("{}", Arc::new("Hi!")); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment