Skip to content

Give futures::executor::ThreadPool a possibility to wait for completion #2461

Open
@TobiasJacob

Description

@TobiasJacob

Consider the following example for the threadpool, which is close to the example from the documentation:

https://docs.rs/futures/0.3.15/futures/executor/struct.ThreadPool.html

use std::thread::sleep;
use std::time::Duration;

use futures::FutureExt;
use futures::executor::ThreadPool;

async fn cpu_intensive(i: u64) {
    let mut res: u64 = 0;
    for j in 0..23 {
        for k in 0..256 {
            res += j + i + k;
            res %= 91349;
        }
        // Imagine that here an async API call is required, so we want another future to continue while this future is waiting for the API result 
    }
    println!("{}: {}", i, res)
}

fn main() {
    let pool = ThreadPool::new().unwrap();
    for i in 0..1000 {
        let fut = cpu_intensive(i);
        pool.spawn_ok(fut)
    }
    // NEEDED: A way to wait for the thread pool to run until completion
    sleep(Duration::from_secs(2));
}

It would be great if there was a way to block main until all futures of the ThreadPool are completed.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions