3 个不稳定版本

0.3.1 2023 年 12 月 13 日
0.3.0 2023 年 12 月 5 日
0.2.4 2023 年 12 月 1 日
0.2.3 2023 年 12 月 1 日
0.2.2 2023 年 12 月 1 日

并发 中排名第 353

每月下载量 46

MIT 许可证 MIT

13KB
142

rpools

Crates.io Crates.io Downloads Rust Stable License GitHub Actions Workflow Status

rpools 是一个使用通道同步任务的极简 Rust 工作池实现。它可以启动固定数量的工作线程,这些线程等待任务队列。

安装

$ cargo add rpools

用法

  • 简单的工作池
 use rpools::pool::WorkerPool;
 use std::sync::mpsc::channel;
 use std::sync::{Arc, Mutex};

 let n_workers = 4;
 let n_jobs = 8;
 let pool = WorkerPool::new(n_workers);

 let (tx, rx) = channel();
 let atx = Arc::new(Mutex::new(tx));
 for _ in 0..n_jobs {
     let atx = atx.clone();
     pool.execute(move|| {
         let tx = atx.lock().unwrap();

            // a long task goes here
            // send results to channel (use it to sync the pool with the parent thread)

         tx.send(1).expect("channel will be there waiting for the pool");
     });
 }

 assert_eq!(rx.iter().take(n_jobs).fold(0, |a, b| a + b), 8);
  • 使用 sync 模块来同步您的池
let njobs = 20;
let nworkers = 3;
let pool = pool::WorkerPool::new(nworkers);
let atomic = Arc::new(AtomicUsize::new(0));
let wg = WaitGroup::default();

// send the jobs to the pool
for _ in 0..njobs {
    let wg = wg.clone();
    let atomic = atomic.clone();
    pool.execute(move || {
        atomic.fetch_add(1, Ordering::Relaxed);
        drop(wg);
    });
}

// wait for the pool finnishes
wg.wait();
assert_eq!(njobs, atomic.load(Ordering::Relaxed));

无运行时依赖项