thread_pool/
thread_pool.rs

1/// Thread pool example
2use rustpool::{ThreadPool, ThreadPoolBuilder};
3
4fn main() {
5    // change USE_ALL_CPUS to target multiple or a single CPU
6    const USE_ALL_CPUS: bool = false;
7
8    let cpu = ThreadPool::get_cpus()[0];
9
10    let builder: ThreadPoolBuilder;
11    if USE_ALL_CPUS {
12        builder = ThreadPoolBuilder::new().for_all_cpus().count(2);
13    } else {
14        builder = ThreadPoolBuilder::new().for_cpu(cpu).count(2);
15    }
16    let res = builder.build();
17
18    if res.is_ok() {
19        println!("Thread pool created");
20        let tp = res.unwrap();
21
22        tp.schedule_task(|| print_task_info(1));
23        tp.schedule_task(|| print_task_info(2));
24
25        // on drop, the pool will wait for all running tasks to end
26        return;
27    }
28
29    // panic if we can't create the thread pool
30    std::panic::panic_any(res.err());
31}
32
33fn print_task_info(task_id: u16) {
34    println!("Task {} executed in thread - {:?}", task_id, std::thread::current().id());
35    let thread_cpus = ThreadPool::get_cpus();
36
37    println!("CPU count available to task {}: {}", task_id, thread_cpus.len());
38    std::thread::sleep(std::time::Duration::from_millis(1000));
39}