async-cpupool/examples/demo.rs
2024-04-15 17:59:13 -05:00

61 lines
1.4 KiB
Rust

#[cfg(not(loom))]
use std::time::Duration;
#[cfg(not(loom))]
use tracing_subscriber::{fmt, prelude::*, EnvFilter};
#[cfg(not(loom))]
fn main() -> Result<(), Box<dyn std::error::Error>> {
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()?;
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?;
tracing::info!("Awaited {i}");
}
// ramp down
for _ in 0..10 {
pool.spawn(move || {
std::thread::sleep(Duration::from_millis(400));
})
.await?;
}
assert!(pool.close().await);
Ok(())
})
}
#[cfg(loom)]
fn main() {}