4 个版本
0.3.3 | 2024年7月29日 |
---|---|
0.3.2 | 2023年6月27日 |
0.2.2 | 2023年6月26日 |
0.1.0 |
|
#344 in 并发
每月 137 次下载
33KB
539 行
Rust 线程池执行器
一个简单的线程池,用于在工作线程上运行作业。您可以指定核心工作者,它们将随着线程池的存在而存在,最大工作者,它们将在给定的保持活动时间内存在,以及当提交的作业数量超过工作者的最大大小时的处理策略。
使用方法
创建一个固定大小的线程池,当作业提交时,如果所有工作者都忙碌,将等待
let pool = threadpool_executor::ThreadPool::new(1);
let mut expectation = pool.execute(|| {"hello, thread pool!"}).unwrap();
assert_eq!(expectation.get_result().unwrap(), "hello, thread pool!");
您可以处理等待特定时间的返回结果
let pool = threadpool_executor::ThreadPool::new(1);
let r = pool.execute(|| {
std::thread::sleep(std::time::Duration::from_secs(10));
});
let res = r.unwrap().get_result_timeout(std::time::Duration::from_secs(3));
assert!(res.is_err());
if let Err(err) = res {
matches!(err.kind(), threadpool_executor::error::ErrorKind::TimeOut);
}
使用 Builder
创建线程池
let pool = threadpool_executor::threadpool::Builder::new()
.core_pool_size(1)
.maximum_pool_size(3)
.keep_alive_time(std::time::Duration::from_secs(300))
.exeed_limit_policy(threadpool_executor::threadpool::ExceedLimitPolicy::Wait)
.build();
在此线程池中运行的工作者将尝试使用您提交的函数中的 std::panic::catch_unwind
捕获 Panic!
,如果捕获到,则 get_result
方法将返回一个 Panic
类型的 ExecutorError。
let pool = threadpool_executor::ThreadPool::new(1);
let r = pool.execute(|| {
panic!("panic!!!");
});
let res = r.unwrap().get_result();
assert!(res.is_err());
if let Err(err) = res {
matches!(err.kind(), threadpool_executor::error::ErrorKind::Panic);
}
您可以在任务等待时取消任务。任务开始运行时不能取消。
let pool = threadpool_executor::ThreadPool::new(1);
pool.execute(|| {
std::thread::sleep(std::time::Duration::from_secs(3));
}).unwrap();
let mut exp = pool.execute(|| {}).unwrap();
exp.cancel();
依赖关系
~435KB