"首次提交"

This commit is contained in:
2024-06-08 15:01:12 +08:00
parent 6e0f708d0a
commit 84349a2469
112 changed files with 3272 additions and 0 deletions

1
p16.fearless_conscurrency/mutex/.gitignore vendored Executable file
View File

@ -0,0 +1 @@
/target

View File

@ -0,0 +1,8 @@
[package]
name = "mutex"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

View File

@ -0,0 +1,33 @@
fn main() {
println!("Hello, world!");
mutex_learn();
}
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
fn mutex_learn() {
let strings = Arc::new(Mutex::new(vec![]));
let mut ths = vec![];
for i in 1..10 {
let strings = Arc::clone(&strings); //获得一个强引用
let handle = thread::spawn(move || {
for _i in 1..3 {
strings
.lock()
.unwrap()
.push(String::from(format!("thread{}: ", i)) + &(i + _i).to_string());
thread::sleep(Duration::from_micros(
(((1 as f64) / (i as f64)) * 100.0) as u64, //线程越前的睡的越久
));
}
});
ths.push(handle);
}
for th in ths {
th.join().unwrap();
}
println!("strings is {:?}", strings.lock().unwrap());
}