base-threadpool

Crates.iobase-threadpool
lib.rsbase-threadpool
version0.0.3
sourcesrc
created_at2024-08-10 20:30:17.528686
updated_at2024-10-04 10:18:06.653798
descriptionminimalistic threadpool implementation
homepage
repository
max_upload_size
id1332685
size19,709
lachezar kolev (lbkolev)

documentation

README

Threadpool

Threadpool provides a way to manage and execute tasks concurrently using a fixed number of worker threads. It allows you to submit tasks that will be executed by one of the available worker threads, providing an efficient way to parallelize work across multiple threads.

Maintaining a pool of threads over creating a new thread for each task has the benefit that thread creation and destruction overhead is restricted to the initial creation of the pool.

The implementation is dependency and unsafe-free.

Usage

use base_threadpool::{ThreadPool, ThreadPoolBuilder};
use std::sync::{Arc, Mutex};

let thread_pool = ThreadPoolBuilder::default().build();
let value = Arc::new(Mutex::new(0));

(0..4).for_each(move |_| {
    let value = Arc::clone(&value);
    thread_pool.execute(move || {
        let mut ir = 0;
        (0..100_000_000).for_each(|_| {
            ir += 1;
        });

        let mut lock = value.lock().unwrap();
        *lock += ir;
    });
});

You can create a ThreadPool using the builder pattern:

use base_threadpool::ThreadPool;

let pool = ThreadPool::builder().build();
let custom_pool = ThreadPool::builder()
    .num_threads(4)
    .stack_size(3 * 1024 * 1024)
    .name_prefix("worker".to_string())
    .build();

Use the execute method to submit tasks to the thread pool:

pool.execute(|| {
    println!("task executed by a thread in the pool");
});

To wait for all tasks to complete:

pool.join();

License

MIT

Commit count: 0

cargo fmt