并发¶
多线程¶
fn main() {
print!("\n");
let fn_thread = thread::spawn(|| loop {
println!("你好!");
thread::sleep(time::Duration::from_millis(100)); // sleep 0.1秒
});
fn_thread.join().unwrap(); // 阻塞主线程
}
消息传递¶
use std::{sync::mpsc, thread};
fn main() {
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
let val = String::from("hi");
tx.send(val).unwrap();
});
let received = rx.recv().unwrap(); // 收到值前阻塞
// try_recv() // 不会阻塞
println!("Got: {}",received);
}
Got: hi
use std::{sync::mpsc, thread, time::Duration, vec};
fn main() {
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
let vals = vec![
String::from("Hi"),
String::from("from"),
String::from("the"),
String::from("thread"),
];
for val in vals {
tx.send(val).unwrap();
thread::sleep(Duration::from_millis(1));
}
});
for received in rx {
println!("Got: {}", received);
}
}
output
Got: Hi
Got: from
Got: the
Got: thread
共享内存¶
use std::sync::Mutex;
fn main() {
let m = Mutex::new(5);
{
let mut num = m.lock().unwrap();
*num = 6;
}
println!("m = {:?}", m);
}
m = Mutex { data: 6, poisoned: false, .. }
Mutex可能产生死锁
其他¶
可以使用Arc<\T>, 用法与Rc<\T>类似
使用Send 和 Sync trait拓展并发,但是手动实现Send 和 Sync是不安全的
Arc<\T>