如题所示,直接上代码了。
一、安装库
[dependencies]
threadpool = "1.8.1"
二、代码
use threadpool::ThreadPool;
fn main() {
let pool = ThreadPool::new(30);//开启30个线程
for i in 1..=6 {
pool.execute(move || {
println!("number {} from the spawned_1 thread!", i);
});
}
for i in 1..=6 {
pool.execute(move || {
println!("number {} from the spawned_2 thread!", i);
});
}
for i in 1..=5 {
println!("number {} from the main thread!", i);
}
pool.join();
}
使用线程池的好处是,避免内存过度使用。