fnmain() { let a = Rc::new(Cons(5, Rc::new(Cons(10, Rc::new(Nil))))); println!("count after creating a = {}", Rc::strong_count(&a)); let b = Cons(3, Rc::clone(&a)); println!("count after creating b = {}", Rc::strong_count(&a)); { let c = Cons(4, Rc::clone(&a)); println!("count after creating c = {}", Rc::strong_count(&a)); } println!("count after c goes out of scope = {}", Rc::strong_count(&a)); }
fnmain() { let handle = thread::spawn(|| { for i in1..10 { println!("hi number {} from the spawned thread!", i); thread::sleep(Duration::from_millis(1)); } });
for i in1..5 { println!("hi number {} from the main thread!", i); thread::sleep(Duration::from_millis(1)); } handle.join().unwrap();// 阻塞等待子线程 }
子线程中可以捕获主线程的变量,获得所有权. 使用move,以免主线程把它drop了:
1 2 3 4 5 6 7 8 9 10 11
use std::thread;
fnmain() { let v = vec![1, 2, 3];
let handle = thread::spawn(move || { println!("Here's a vector: {:?}", v); });
handle.join().unwrap(); }
消息传递: channel
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
use std::thread; use std::sync::mpsc;
fnmain() { let (tx, rx) = mpsc::channel(); // tx: 发送者 // rx: 接收者 thread::spawn(move || { let val = String::from("hi"); tx.send(val).unwrap();// 单所有权,发送后不能再使用val });
let received = rx.recv().unwrap(); println!("Got: {}", received); }
mpsc: 多生产者、单消费者 recv: 阻塞接收 try_recv: 非阻塞接收,立即返回
这里之所以是多生产者,是因为可以把生产者无限克隆出去,然后发送消息:
1
let tx1 = mpsc::Sender::clone(&tx);
共享状态并发
互斥器(mutex)
rust中的锁是一种特殊的智能指针,通过重载drop trait来确保离开作用域的时候释放锁。
1 2 3 4 5 6 7 8 9
use std::sync::Mutex; fnmain() { let m = Mutex::new(5); { letmut num = m.lock().unwrap(); *num = 6; } println!("m = {:?}", m); }