Skip to content

Instantly share code, notes, and snippets.

@ilopX
Created January 24, 2025 23:43
Show Gist options
  • Save ilopX/fd42247cd34207e0190ed7a2968605e5 to your computer and use it in GitHub Desktop.
Save ilopX/fd42247cd34207e0190ed7a2968605e5 to your computer and use it in GitHub Desktop.
use std::sync::{Arc, Mutex, RwLock};
use std::thread::scope;
fn main() {
for guard_factory in guard_factories() {
let guard = Arc::new(guard_factory());
scope(|s| {
for n in 0..10 {
let guard_rc = guard.clone();
s.spawn(move || {
guard_rc.add(n);
print(guard_rc, n);
});
}
});
println!("{:?}", guard.get());
println!("ok");
}
}
fn guard_factories() -> Vec<fn() -> Box<dyn Guard>> {
[|| GuardMutex::new(), || GuardRwLock::new()].into()
}
fn print(guard: Arc<Box<dyn Guard>>, n: i32) {
println!(
"type: {}, thread: {:?}, push({n})",
guard.name(),
std::thread::current().id(),
);
}
trait Guard: Send + Sync {
fn add(&self, val: i32);
fn get(&self) -> String;
fn name(&self) -> &str;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
struct GuardMutex {
vec: Mutex<Vec<i32>>,
}
impl GuardMutex {
fn new() -> Box<dyn Guard> {
Box::new(GuardMutex {
vec: Mutex::new(vec![]),
})
}
}
impl Guard for GuardMutex {
fn add(&self, val: i32) {
self.vec.lock().unwrap().push(val);
}
fn get(&self) -> String {
format!("{:?}", self.vec.lock().unwrap())
}
fn name(&self) -> &str {
"Mutex"
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
struct GuardRwLock {
vec: RwLock<Vec<i32>>,
}
impl GuardRwLock {
fn new() -> Box<dyn Guard> {
Box::new(Self {
vec: RwLock::new(vec![]),
})
}
}
impl Guard for GuardRwLock {
fn add(&self, val: i32) {
self.vec.write().unwrap().push(val);
}
fn get(&self) -> String {
format!("{:?}", self.vec.read().unwrap())
}
fn name(&self) -> &str {
"RwLock"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment