Skip to content

tokio::spawn future cannot be sent between threads safely #3886

Answered by Darksonn
FH0 asked this question in Q&A
Discussion options

You must be logged in to vote

This topic is covered in the shared state chapter of the Tokio tutorial. The first question you should ask yourself is if you really need a lock at all. For example, could this work?

use std::time::Duration;

#[tokio::main]
async fn main() {
    let timeout = Duration::from_secs(1);
    tokio::spawn(async move {
        tokio::time::sleep(timeout).await;
    });
}

If you do need a lock for the purpose of having a shared value you can modify from several places, a good way to get cleaner code is to define the following helper struct:

use std::time::Duration;
use std::sync::{Arc, RwLock};

#[derive(Clone)]
pub struct SharedDuration {
    inner: Arc<RwLock<Duration>>,
}

impl SharedDuration {

Replies: 2 comments

Comment options

You must be logged in to vote
0 replies
Answer selected by FH0
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants
Converted from issue

This discussion was converted from issue #3885 on June 23, 2021 13:26.