视频地址
头条地址:https://www.ixigua.com/i6775861706447913485
B站地址:https://www.bilibili.com/video/av81202308/
源码地址
github地址:https://github.com/anonymousGiga/learn_rust
讲解内容
1、线程间共享Mutex
(1)错误例子:
```
use std::sync::Mutex;
use std::thread;
fn main() {
let counter = Mutex::new(0);
let mut handles = vec![];
for _ in 0…10 {
let handle = thread::spawn(move || {
let mut num = counter.lock().unwrap();
*num += 1;
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
println!(“Result: {}”, *counter.lock().unwrap());
}
错误原因:不能将counter锁的所有权移动到多个线程中。
(2)错误例子2:通过Rc<T>来创建引用计数的值
use std::rc::Rc;
use std::sync::Mutex;
use std::thread;
fn main() {
let counter = Rc::new(Mutex::new(0));
let mut handles = vec![];
for _ in 0…10 {
let counter = Rc::clone(&counter);
let handle = thread::spawn(move || {
let mut num = counter.lock().unwrap();
*num += 1;
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
println!(“Result: {}”, *counter.lock().unwrap());
}
错误原因:Rc<T>不是线程安全的
(3)例子3:使用Arc<T>
说明: Arc<T>是一个类似于Rc<T>并可以安全的用于并发环境的类型,代码如下:
use std::sync::{Mutex, Arc};
use std::thread;
fn main() {
let counter = Arc::new(Mutex::new(0));
let mut handles = vec![];
for _ in 0..10 {
let counter = Arc::clone(&counter);
let handle = thread::spawn(move || {
let mut num = counter.lock().unwrap();
*num += 1;
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
println!("Result: {}", *counter.lock().unwrap());
}
2、RefCell<T>/Rc<T> 与 Mutex<T>/Arc<T> 的相似性
(1)Mutex<T>提供内部可变性,类似于RefCell;
(2)RefCell<T>/Rc<T>是非线程安全的,而Mutex<T>/Arc<T>是线程安全的。