I am attempting to add a job to a thread pool that has to be able to also add jobs to that thread pool.
I am new to Rust.
I am attempting to use this to pass a function as a job to a thread pool. This function needs to be able to call itself more times (would have changing parameters but I've omitted them) and so all thread can be used, it needs to add these subsequent function calls as jobs to the thread pool. I have tried many things but I can't figure out how to pass a reference of the thread pool into the job.
Example:
use num_cpus;
use threadpool::ThreadPool;
fn func2(pool: &ThreadPool) {
pool.execute(|| func2(&pool))
}
fn func1() {
let pool = ThreadPool::new(num_cpus::get());
pool.execute(|| func2(&pool));
pool.join();
}
You could place the threadpool in an Arc, and pass the cloned Arc to the function. However ThreadPool
provides cheap clone()
that already behaves like an Arc, giving you a new handle to the same thread pool. That means you can simply clone the thread pool to pass it along:
use threadpool::ThreadPool;
fn func2(pool: ThreadPool) {
pool.execute({
let pool = pool.clone();
move || func2(pool)
});
}
pub fn func1() {
let pool = ThreadPool::new(num_cpus::get());
pool.execute({
let pool = pool.clone();
move || func2(pool)
});
pool.join();
}
Note that as written, this code (as well as your original one) performs an infinite loop, with func2()
tail-recursively invoking itself via the thread pool.