I have a set of small tasks, split them into chunks, and want to run a function for every chunk in ThreadPool, and be able to wait till all of them end (or panic).
But ThreadPool::install
works in sync manner. It looks like even if I nest it inside another install
call, everything will still be fully sync.
(I thought of just calling spawn
and then monitoring a flag variable. But maybe, there's a better way?)
Here's the snippet:
let results = Arc<Mutex<Vec<usize>>> = Arc::new(Mutex::new(vec![]));
let mut tpool = ThreadPoolBuilder::new().build().unwrap();
for (i, items) in item_chunks.into_iter().enumerate() {
tpool.install(move || {
println!("thread {i} started");
sleep(Duration::from_secs(3));
println!("thread {i} waited 3 secs");
results.lock().unwrap().push(i);
});
}
The output:
thread 0 started
thread 0 waited 3 secs
thread 1 started
thread 1 waited 3 secs
thread 2 started
thread 2 waited 3 secs
thread 3 started
thread 3 waited 3 secs
I want instead them to run in parallel, and then somehow to await/join ThreadPool, and have a guarantee all the tasks are done.