728x90
use std::sync::Mutex;
use std::thread;
trait CoolTrait {
fn cool_function(&self);
}
struct OurStruct {
data: Mutex<u8>
}
impl CoolTrait for OurStruct {
fn cool_function(&self) {
*self.data.borrow_mut() += 1;
}
}
fn main() {
let our_struct = OurStruct {
data: Mutex::new(0)
}
let mut join_vec = vec![];
for _ in 0..10 {
thread::spawn(|| {
*our_struct.borrow_mut() += 1;
});
join_vec.push(join_handle);
}
for handle in join_vec {
handle.join().unwrap();
}
}
use std::sync::{Arc, Mutex};
use std::thread;
trait CoolTrait {
fn cool_function(&self);
}
#[derive(Debug)]
struct OurStruct {
data: Arc::new(Mutex::new(0))
}
impl CoolTrait for OurStruct {
fn cool_function(&self) {
let lock = self.data.lock().unwrap();
drop(lock);
*self.data.borrow_mut() += 1;
}
}
fn main() {
let our_struct = OurStruct {
data: Arc::new(Mutex::new(0))
};
let mut join_vec = vec![];
for _ in 0..10 {
let clone = Arc::clone(&our_struct.data);
let join_handle = thread::spawn(move || {
*clone.lock().unwrap() += 1;
println!("There are {} owners", Arc::strong_count(&clone));
});
join_vec.push(join_handle);
}
for handle in join_vec {
handle.join().unwrap();
}
println!("Our struct is now: {our_struct:?}");
}
use std::sync::{Mutex, RwLock};
fn main() {
/*
let my_mutex = Mutex::new(5);
let mut mutex_changer = my_mutex.lock().unwrap();
let mut other_mutex_changer = my_mutex.try_lock();
if let Ok(value) = other_mutex_changer {
println!("The mutexchanger has: {value}");
} else {
println!("Didn't get a lock");
}
println!("{my_mutex:?}");
*/
let my_rwlock = RwLock::new(5);
let read1 = my_rwlock.read().unwrap();
let read2 = my_rwlock.read().unwrap();
println!("{read1:?}, {read2:?}");
}
728x90
'Rust' 카테고리의 다른 글
[Rust lang] 86. box (0) | 2023.03.30 |
---|---|
[Rust lang] 85. clippy (0) | 2023.03.30 |
[Rust lang] 83. multiple threads (0) | 2023.03.30 |
[Rust lang] 82. cow (0) | 2023.03.30 |
[Rust lang] 81. type alias and todo macro (0) | 2023.03.30 |
댓글