"首次提交"

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/thread/.gitignore vendored Executable file
View File

@ -0,0 +1 @@
/target

View File

@ -0,0 +1,8 @@
[package]
name = "thread"
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,98 @@
fn main() {
println!("Hello, world!");
thread_learn();
thread_learn1();
thread_learn2();
}
use std::thread;
use std::time::Duration;
fn thread_learn() {
let handle = thread::spawn(|| {
for i in 1..5 {
println!("thread {}", i);
thread::sleep(Duration::from_millis(100));
}
});
for i in 1..5 {
println!("main {}", i);
thread::sleep(Duration::from_millis(50));
}
handle.join().unwrap();
}
fn thread_learn1() {
let v = vec![1, 2, 3, 4];
//闭包是可以直接捕获上下文中的变量并使用的但是在线程里不行。因为rust无法获知线程合适结束也就
//无法保证v的有效性。如果需要在threa里使用主线程中的变量。需要使用move将其移动到子线程
//这样主线程也就不在拥有v的所有权了
/* 这种方式会编译不过。因为v不可以再子线程使用 */
// let handle = thread::spawn(|| {
// println!("thread {:?}", v);
// });
// println!("main {:?}", v);
/* 这种方式会编译不过。因为v被移动到子线程主线程已不可使用 */
let handle = thread::spawn(move || {
println!("thread {:?}", v);
});
//println!("main {:?}", v);
handle.join().unwrap();
}
use std::sync::mpsc;
fn thread_learn2() {
let (tx, rx) = mpsc::channel();
let tx1 = mpsc::Sender::clone(&tx); //再产生一个生产者
let handle = thread::spawn(move || {
let val = String::from("hello");
tx.send(val).unwrap();
let msgs = vec!["aaaa", "qwer", "rty", "byebye", "zaas"];
for msg in msgs {
match tx.send(String::from(msg)) {
Err(err) => {
println!("发送失败 {:?}", err);
break;
}
_ => {}
}
thread::sleep(Duration::from_micros(20));
}
});
let thandle1 = thread::spawn(move || {
let val = String::from("hello");
tx1.send(val).unwrap();
let msgs = vec!["aaaa1", "qwer1", "rty1", "byebye1", "zaas1"];
for msg in msgs {
match tx1.send(String::from(msg)) {
Err(err) => {
println!("发送失败 {:?}", err);
break;
}
_ => {}
}
thread::sleep(Duration::from_micros(5));
}
});
let handle1 = thread::spawn(move || loop {
let val = match rx.try_recv() {
Ok(msg) => msg,
Err(_) => {
thread::sleep(Duration::from_millis(10));
continue;
}
};
// let val = rx.recv().unwrap();
if val == "byebye" {
drop(rx);
break;
}
println!("receive a msg: {}", val);
});
handle.join().unwrap();
thandle1.join().unwrap();
handle1.join().unwrap();
}