单线程阻塞
fn get_two_sites() {
// Handle two task in a row.
download("https://www.foo.com");
download("https://www.bar.com");
}
单线程方式必须执行完一个任务才能执行下一个,一个系统线程也会造成长时间阻塞,总任务处理时间长。
多线程阻塞
fn get_two_sites() {
// Spawn two threads to do work.
let thread_one = thread::spawn(|| download("https://www.foo.com"));
let thread_two = thread::spawn(|| download("https://www.bar.com"));
// Wait for both threads to complete.
thread_one.join().expect("thread one panicked");
thread_two.join().expect("thread two panicked");
}
开启独立的线程分别执行两个任务,总的执行时长取决于执行慢的任务,并发程度高,但开启大量线程会增加系统上下文开销。
异步
Rust 中将任务抽象成 Future
,在执行每个 Future
时,如果发生阻塞,就会让出当前的线程控制权,允许其它 future 运行,这样可以极大的利用操作系统的线程。
async fn get_two_sites_async() {
// Create two different "futures" which, when run to completion,
// will asynchronously download the webpages.
let future_one = download_async("https://www.foo.com");
let future_two = download_async("https://www.bar.com");
// Run both futures to completion at the same time.
join!(future_one, future_two);
}