# How to run a thread in background?

**URL:** <https://users.rust-lang.org/t/how-to-run-a-thread-in-background/68737>\
**Category:** help\
**Created:** [December 13, 2021, 12:57pm UTC](https://users.rust-lang.org/t/how-to-run-a-thread-in-background/68737 "2021-12-13T12:57:27Z")\
**Posts on this page:** 6\
**Page:** 1

<div class="post-metadata">

**Author:** ![goldwind-ting](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/goldwind-ting/32/23589_2.png) [@goldwind-ting](https://users.rust-lang.org/u/goldwind-ting)\
**Post date:** [December 13, 2021, 12:57pm UTC](https://users.rust-lang.org/t/how-to-run-a-thread-in-background/68737/1 "2021-12-13T12:57:27Z")

</div>

```rust
use futures::future::{BoxFuture, Future, join_all};
use tokio::sync::Mutex;
use tokio::time::{self, Duration};
#[macro_use]
extern crate lazy_static;
use std::sync::Arc;

async fn a_job() {
    std::thread::sleep(Duration::from_secs(1));
    println!("I am working with a_job!");
}

async fn b_job() {
    std::thread::sleep(Duration::from_secs(10));
    println!("I am working with b_job!");
}

struct Job<R> {
    func: Box<dyn Fn() -> BoxFuture<'static, R> + Send + Sync + 'static>,
}

impl<R> Job<R> {
    fn new<F>(f: fn() -> F) -> Job<F::Output>
    where
        F: Future<Output = R> + Send + 'static,
    {
        Job {
            func: Box::new(move || Box::pin(f())),
        }
    }
    async fn run(&self) -> R {
        (self.func)().await
    }
}

lazy_static! {
    static ref GLOBAL: Arc<Mutex<Vec<Job<()>>>> = Arc::new(Mutex::new(vec![Job::new(a_job), Job::new(b_job)]));
}

#[tokio::main]
async fn main() {
    let recv_trigger = tokio::spawn(async move {
        let mut interval = time::interval(time::Duration::from_secs(1));
        loop {
            tokio::select! {
               _ = interval.tick() => {
                let global = GLOBAL.clone();
                let mut v = global.lock().await;
                let mut tasks = Vec::new();
                for job in v.iter_mut(){
                    tasks.push(job.run()); 
                }
                join_all(tasks).await;
               }
            }
        }
    });

    let _ = tokio::join!(recv_trigger);
}

```

I encounter a problem, when the `interval.tick() ` is true, the `b_job` and `a_job` wait 10 seconds synchronously, but I want `b_job` and `a_job` to wait in background, and print:

```rust
I am working with a_job!
I am working with a_job!
I am working with a_job!
I am working with a_job!
I am working with a_job!
I am working with a_job!
I am working with a_job!
I am working with a_job!
I am working with a_job!
I am working with a_job!
I am working with b_job!
I am working with a_job!
.....

```

it just is similar to `go` keyword in golang, so how to implement it? 😂

---

<div class="post-metadata">

**Author:** ![steffahn](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/steffahn/32/47569_2.png) [@steffahn](https://users.rust-lang.org/u/steffahn)\
**Post date:** [December 13, 2021, 1:07pm UTC](https://users.rust-lang.org/t/how-to-run-a-thread-in-background/68737/2 "2021-12-13T13:07:11Z")

</div>

If you use `join_all` on futures, they are executed in a sort of “[cooperative multitasking](https://en.wikipedia.org/wiki/Cooperative_multitasking)” manner on the same thread. Multi-threading with async code execution happens, too, on a per-task basis when you use `tokio::spawn` to spawn tasks; even then the parallelization is limited to a fixed set of worker thread. In either case, you need to ensure that no task is unnecessarily _blocking_ the execution, that’s the “cooperative” part of “cooperative multitasking”: bad players can starve the whole system.

Now, `std::thread::sleep` _ **is** _ a blocking function call; a “bad player” so to speak. Or put differently: You’re using a _synchronous_ sleep primitive (`thread::sleep`) in an _asynchronous_ environment (`async fn`s, executed on `tokio`’s executor). To fix the problem, you’ll need to replace

```rust
std::thread::sleep(Duration::from_secs(10));

```

with

```rust
tokio::time::sleep(Duration::from_secs(10)).await;

```

(you might need to enable the `time` feature of `tokio` in your `Cargo.toml`)

* * *

_Edit:_ For further background, [this is a cool explanation I’ve found online](https://stackoverflow.com/a/48736148).

---

<div class="post-metadata">

**Author:** ![goldwind-ting](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/goldwind-ting/32/23589_2.png) [@goldwind-ting](https://users.rust-lang.org/u/goldwind-ting)\
**Post date:** [December 13, 2021, 2:42pm UTC](https://users.rust-lang.org/t/how-to-run-a-thread-in-background/68737/3 "2021-12-13T14:42:57Z")

</div>

Sorry, I didn't mean that 😂, I mean, is there any way to run task and wait in background? When the interval is activated, `a_job` and `b_job` run and wait task in background, after a one-second delay,`interval` is activated again without waiting for threads spawned by `a_job` and `b_job` finish, it is just like golang: `go a_job()`.

---

<div class="post-metadata">

**Author:** ![steffahn](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/steffahn/32/47569_2.png) [@steffahn](https://users.rust-lang.org/u/steffahn)\
**Post date:** [December 13, 2021, 3:23pm UTC](https://users.rust-lang.org/t/how-to-run-a-thread-in-background/68737/4 "2021-12-13T15:23:05Z")

</div>

As mentioned, you can run _tasks_ in the background with `tokio::spawn`. Your functions `a_job` and `b_job` are terrible functions because they’re `async fn`, yet block execution _synchronously_ for multiple seconds. If these things are stand-ins for something else, there’s three possibilites I can come up with: Either they are computation-intensive jobs, in which case they should not be `async fn`s, and tokio might be the wrong framework for executing those; but you could try using [`tokio::spawn_blocking`](https://docs.rs/tokio/1/tokio/task/fn.spawn_blocking.html) in order to execute them in a large pool of allowed-to-be-blocking worker threads; or they’re handling some form of IO _synchronously_, in which case you should consider making them _asynchronous_ instead (in this example the mentioned transition from `std::tread` to `tokio::time`) or you could turn them into non-`async` functions and use `spawn_blocking` as-well (usually less efficient and less scalable), or they’re already _asynchronous_ tasks, ( **_they aren’t in your example where they use `thread::sleep`!_** ), in which case you can use `tokio::spawn` to start them in the background. With `tokio::spawn`, you don’t need to keep and await the returned handle, if you’re not interested in observing the result/completion of the spawned task. You can just drop the handle and it will keep running in the background.

---

<div class="post-metadata">

**Author:** ![goldwind-ting](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/goldwind-ting/32/23589_2.png) [@goldwind-ting](https://users.rust-lang.org/u/goldwind-ting)\
**Post date:** [December 13, 2021, 4:29pm UTC](https://users.rust-lang.org/t/how-to-run-a-thread-in-background/68737/5 "2021-12-13T16:29:41Z")

</div>

I am sorry, I got it wrong, thank you!

---

<div class="post-metadata">

**Author:** ![system](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/system/32/51372_2.png) [@system](https://users.rust-lang.org/u/system)\
**Post date:** [March 13, 2022, 4:30pm UTC](https://users.rust-lang.org/t/how-to-run-a-thread-in-background/68737/6 "2022-03-13T16:30:13Z")

</div>

Closed on March 13, 2022, 4:30pm UTC

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.
