(tokio::spawn) 借用的值不够长——参数要求为 static 借用 sleepy

(tokio::spawn) borrowed value does not live long enough -- argument requires that `sleepy` is borrowed for `'static`

这个 MWE 展示了 tokio::spawnfor in 循环中的使用。注释代码 sleepy_futures.push(sleepy.sleep_n(2)); 工作正常,但不 run/poll 异步函数。

基本上,我想同时运行一堆异步函数。我很高兴更改 Sleepy 的实现或使用另一个 library/technique.

pub struct Sleepy;
impl Sleepy {
    pub async fn sleep_n(self: &Self, n: u64) -> String {
        sleep(Duration::from_secs(n));
        "test".to_string()
    }
}

#[tokio::main(core_threads = 4)]
async fn main() {
    let sleepy = Sleepy{};

    let mut sleepy_futures = vec::Vec::new();
    for _ in 0..5 {
        // sleepy_futures.push(sleepy.sleep_n(2));
        sleepy_futures.push(tokio::task::spawn(sleepy.sleep_n(2)));
    }

    let results = futures::future::join_all(sleepy_futures).await;
    for result in results {
        println!("{}", result.unwrap())
    }
}

这是修复它的粗略尝试:

use tokio::time::delay_for;

pub struct Sleepy;
impl Sleepy {
    pub async fn sleep_n(n: u64) -> String {
        delay_for(Duration::from_secs(n)).await;
        "test".to_string()
    }
}

现在它不再锚定到任何特定的 Sleepy 实例,从而消除了生命周期问题。你可以这样称呼它 Sleepy::sleep_n.

如果需要 &self,则需要多做一些工作:

use std::sync::Arc;
use std::time::Duration;
use std::vec;
use tokio;
use tokio::time::delay_for;

pub struct Sleepy;
impl Sleepy {
    pub async fn sleep_n(&self, n: u64) -> String {
        // Call .await here to delay properly
        delay_for(Duration::from_secs(n)).await;
        "test".to_string()
    }
}

#[tokio::main(core_threads = 4)]
async fn main() {
    env_logger::init();

    let sleepy = Arc::new(Sleepy {});

    let mut sleepy_futures = vec::Vec::new();
    for _ in 0..5 {
        let sleepy = sleepy.clone();

        // Dictate that values are moved into the task instead of 
        // being borrowed and dropped.  
        sleepy_futures.push(tokio::task::spawn(async move {
            sleepy.sleep_n(2).await
        }));
    }

    let results = futures::future::join_all(sleepy_futures).await;
    for result in results {
        println!("{}", result.unwrap())
    }
}

这里用Arc来包装对象,因为task可能会用到线程,所以Rc是不够的。