1 个不稳定版本

0.0.2 2024年8月10日
0.0.1 2024年8月10日

#432并发

Download history 178/week @ 2024-08-05 57/week @ 2024-08-12

每月 235 次下载

MIT 许可证

18KB
246

线程池

线程池提供了一种使用固定数量的工作线程来管理和执行任务的方法。它允许您提交将由可用的任何一个工作线程执行的作业,从而为跨多个线程并行化工作提供了一种有效的方法。

与为每个任务创建一个新的线程相比,维护一个线程池的好处是,线程的创建和销毁开销仅限于池的初始创建,这可能会导致更好的性能。

实现是依赖项和无 不安全 的。

使用方法

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;
    });
});

您可以使用构建器模式创建 ThreadPool

use base_threadpool::ThreadPool;

// create a thread pool with default settings
let pool = ThreadPool::builder().build();

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

使用 execute 方法将任务提交到线程池

pool.execute(|| {
    // Your task here
    println!("Task executed by thread pool");
});

等待所有任务完成

pool.join();

许可证

MIT

无运行时依赖