单线程阻塞

  1. fn get_two_sites() {
  2. // Handle two task in a row.
  3. download("https://www.foo.com");
  4. download("https://www.bar.com");
  5. }

单线程方式必须执行完一个任务才能执行下一个,一个系统线程也会造成长时间阻塞,总任务处理时间长。

多线程阻塞

  1. fn get_two_sites() {
  2. // Spawn two threads to do work.
  3. let thread_one = thread::spawn(|| download("https://www.foo.com"));
  4. let thread_two = thread::spawn(|| download("https://www.bar.com"));
  5. // Wait for both threads to complete.
  6. thread_one.join().expect("thread one panicked");
  7. thread_two.join().expect("thread two panicked");
  8. }

开启独立的线程分别执行两个任务,总的执行时长取决于执行慢的任务,并发程度高,但开启大量线程会增加系统上下文开销。

异步

Rust 中将任务抽象成 Future ,在执行每个 Future 时,如果发生阻塞,就会让出当前的线程控制权,允许其它 future 运行,这样可以极大的利用操作系统的线程。

  1. async fn get_two_sites_async() {
  2. // Create two different "futures" which, when run to completion,
  3. // will asynchronously download the webpages.
  4. let future_one = download_async("https://www.foo.com");
  5. let future_two = download_async("https://www.bar.com");
  6. // Run both futures to completion at the same time.
  7. join!(future_one, future_two);
  8. }