Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

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

This MWE shows the use of tokio::spawn in for in loop. The commented code sleepy_futures.push(sleepy.sleep_n(2)); works fine, but does not run/poll the async function.

Basically, I would like to run a bunch of async functions at the same time. I am happy to change the implementation of Sleepy or use another 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())
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here's a rough stab at fixing it:

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()
    }
}

Where now it's no longer anchored to any particular Sleepy instance, eliminating the lifetime issue. You'd call it like Sleepy::sleep_n.

It takes a little more work if that &self is required:

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())
    }
}

Here Arc is used to wrap the object since task may use threads, so Rc isn't sufficient.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...