async-cpupool/examples/demo.rs

56 lines
1.4 KiB
Rust

use std::time::Duration;
use tracing_subscriber::{fmt, prelude::*, EnvFilter};
fn main() {
tracing_subscriber::registry()
.with(fmt::layer())
.with(EnvFilter::from_default_env())
.init();
let pool = async_cpupool::CpuPool::configure()
.min_threads(1)
.max_threads(10)
.buffer_multiplier(8)
.build()
.expect("Valid configuration");
smol::block_on(async {
// scale up
let tasks: Vec<_> = (0..30)
.map(|i| {
let pool = pool.clone();
smol::spawn(async move {
tracing::info!("Spawning");
let out = pool
.spawn(move || {
std::thread::sleep(Duration::from_millis(400));
i
})
.await;
pool.close().await;
out
})
})
.collect();
for task in tasks {
let i = task.await.expect("Got value");
tracing::info!("Awaited {i}");
}
// ramp down
for _ in 0..10 {
pool.spawn(move || {
std::thread::sleep(Duration::from_millis(400));
})
.await
.expect("Got value");
}
assert!(pool.close().await);
})
}