23 个版本
0.2.6 | 2020年7月11日 |
---|---|
0.2.5 | 2019年12月13日 |
0.2.4 | 2019年11月21日 |
0.2.1 | 2019年7月14日 |
0.1.2 | 2018年3月28日 |
#683 in 并发
用于 2 crates
100KB
2K SLoC
线程池
本包提供了一种创建和管理线程池的简便方法,因此您无需...
如何使用
在您的项目 Cargo.toml
中添加依赖项
[dependencies]
threads_pool = "^0.2.0"
然后在您的代码中
extern crate threads_pool;
use std::time::Duration;
use std::thread::sleep;
use threads_pool::*;
fn main() {
// The pool lives as long as the `pool` variable, when pool goes out of
// the scope, the thread pool will be destroyed gracefully -- all threads
// will finish their current job and then garnered.
let pool = ThreadPool::new(8);
for num in 0..100 {
pool.execute(move || {
// Your code here...
println!("I'm in with: {}", num);
sleep(Duration::from_millis(10));
});
}
}
本包还提供了一个静态池,您可以一次性创建它,并在应用程序的任何地方使用它。这被称为 shared_mode
extern crate threads_pool;
use std::time::Duration;
use std::thread::sleep;
use threads_pool::shared_mode;
fn main() {
// Create the pool here, then you can use the pool everywhere. If run a task without
// creating the pool, it will be equivalent of calling 'thread::spawn' on the task.
shared_mode::initialize(8);
for num in 0..100 {
shared_mode::run(move || {
// Your code here...
println!("I'm in with: {}", num);
sleep(Duration::from_millis(10));
});
}
// The static pool must be closed, or unfinished threads will be destroyed prematurely and could cause panic in the
// running threads. this is different from the managed pool where it can know when to shutdown as the allocated pool
// object goes out of the scope.
shared_mode::close();
}
依赖项
~3MB
~46K SLoC