Rust并发编程:线程、通道与async/await
3 阅读
预计 3 分钟
Rust的并发编程以安全著称。本文介绍标准库的线程和通道,以及async/await异步编程。
## 标准库线程
```rust
use std::thread;
use std::time::Duration;
fn main() {
let handle = thread::spawn(|| {
for i in 1..10 {
println!("spawned thread: {}", i);
thread::sleep(Duration::from_millis(1));
}
});
for i in 1..5 {
println!("main thread: {}", i);
thread::sleep(Duration::from_millis(1));
}
handle.join().unwrap();
}
```
## 通道(Channel)
```rust
use std::sync::mpsc;
use std::thread;
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();
}
});
for received in rx {
println!("Got: {}", received);
}
}
```
## async/await
```rust
use tokio;
#[tokio::main]
async fn main() {
let handle = tokio::spawn(async {
println!("hello from tokio task");
42
});
let result = handle.await.unwrap();
println!("Result: {}", result);
}
```
## Send与Sync
- Send:值可以安全地转移到另一个线程
- Sync:值可以安全地被多个线程引用
大多数类型自动实现这两个trait。Rc不实现Send(用Arc替代),RefCell不实现Sync(用Mutex替代)。
Rust的类型系统在编译期就防止了数据竞争,这是其他语言难以做到的。
0 条评论 欢迎参与讨论