项目中碰到了阻塞的问题, 所以来看看怎么使用rust并行.
仅作为个人学习笔记.
参考资料:https://my_lv.gitbooks.io/rust/content/concurrency-parallel-thread/thread.html
其实是照搬

rust并发/并行/多线程

可以用标准库或tokio.标准库见下文.

创建线程

FnMut和FnOnce
FnOnce是会转移所有权的闭包函数,且函数运行后所有权会被释放不会归还.
所以叫FnOnce: 只能运行一次.
FnMut: 使用可变借用的闭包函数,运行后会归还所有权.

1
2
3
4
5
6
let new_thread = thread::spawn(move|| {
// thread code here
})

// 等待线程执行完成
new_thread.join().unwrap();

设置线程名称和堆栈的创建方式:

1
2
3
4
5
6
7
8
let new_thread = thread::Builder::new()
.name("thread1".to_string())
.stack_size(4*1024*1024)
.spawn(move ||{
// thread code here
});
// 等待执行完成
new_thread.unwrap().join().unwrap();

消息传递

和go语言一样 使用channel.
mpsc是多生产者,单消费者.

1
2
3
4
5
6
7
8
9
10
11
let (tx, rx): (mpsc::Sender<i32>, mpsc::Receiver<i32>) = 
mpsc::channel();

// 创建线程用于发送消息
thread::spawn(move || {
// 发送一个消息,此处是数字id
tx.send(1).unwrap();
});

// 在主线程中接收子线程发送的消息并输出
println!("receive {}", rx.recv().unwrap());

使用Arc<>包装并传递自定义类型:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
pub struct Student {
id: u32
}
fn main() {
let (tx, rx): (mpsc::Sender<Arc<Student>>, mpsc::Receiver<Arc<Student>>) =
mpsc::channel();

thread::spawn(move || {
tx.send(Arc::new(Student{
id: 1,
})).unwrap();
});

// 在主线程中接收子线程发送的消息并输出
println!("receive {}", rx.recv().unwrap());
}

try_recv(): 不阻塞,立即返回Result< T,E >.Err表示没有消息.
recv(): 阻塞直到有消息并返回.

使用Arc<Mutex<>>来共享和修改数据.

如何产生多个发送者:
let tx1 = tx.clone()