如何在Rust中实现作用域异步任务?

时间:2019-10-01 11:38:55

标签: rust

我正在尝试在Rust 1.40.0-nightly(8431f261d 2019-09-29)中实现有范围的任务,但是我无法使我的代码编译。

我要简化以下代码:

use async_std::task;
use std::time::Duration;

pub fn main() {
    let mut v = Vec::new();
    v.push(task::spawn(async {
        task::sleep(Duration::from_millis(1000)).await;
        println!("Hello, world!");
    }));
    v.push(task::spawn(async {
        task::sleep(Duration::from_millis(2000)).await;
        println!("Hello, world 2!");
    }));
    for t in &mut v {
        task::block_on(t);
    }
}

我想实现Scope结构,使先前的代码如下:

pub fn main() {
    let mut s = Scope::new();
    s.push(async {
        task::sleep(Duration::from_millis(1000)).await;
        println!("Hello, world 1!");
    });
    s.push(async {
        task::sleep(Duration::from_millis(2000)).await;
        println!("Hello, world 2!");
    });
}

我目前的实现方式是:

struct Scope<T>
where
    T: std::future::Future + std::marker::Unpin,
{
    v: Vec<T>,
}

impl<T> Scope<T>
where
    T: std::future::Future + std::marker::Unpin,
{
    fn new() -> Scope<T> {
        Scope { v: Vec::new() }
    }
    fn push(&mut self, t: T) {
        self.v.push(t);
    }
}

impl<T> Drop for Scope<T>
where
    T: std::future::Future + std::marker::Unpin,
{
    fn drop(&mut self) {
        for t in &mut self.v {
            task::block_on(t);
        }
    }
}

pub fn main() {
    let mut s = Scope::new();
    s.push(async {
        task::sleep(Duration::from_millis(1000)).await;
        println!("Hello, world 1!");
    });
    s.push(async {
        task::sleep(Duration::from_millis(2000)).await;
        println!("Hello, world 2!");
    });
}

但这会导致编译失败,并显示以下错误:

error[E0277]: the trait bound `std::future::GenFuture<[static generator@src/main.rs:36:18: 39:6 _]>: std::marker::Unpin` is not satisfied in `impl std::future::Future`
  --> src/main.rs:36:7
   |
36 |     s.push(async {
   |       ^^^^ within `impl std::future::Future`, the trait `std::marker::Unpin` is not implemented for `std::future::GenFuture<[static generator@src/main.rs:36:18: 39:6 _]>`
   |
   = help: the following implementations were found:
             <std::future::GenFuture<T> as std::marker::Unpin>
   = note: required because it appears within the type `impl std::future::Future`

error[E0599]: no method named `push` found for type `Scope<impl std::future::Future>` in the current scope
  --> src/main.rs:40:7
   |
4  | / struct Scope<T>
5  | | where
6  | |     T: std::future::Future + std::marker::Unpin,
7  | | {
8  | |     v: Vec<T>,
9  | | }
   | |_- method `push` not found for this
...
40 |       s.push(async {
   |         ^^^^ method not found in `Scope<impl std::future::Future>`
   |
   = note: the method `push` exists but the following trait bounds were not satisfied:
           `impl std::future::Future : std::marker::Unpin`

如何解决这些编译问题?

0 个答案:

没有答案