
use std::thread;
fn main() {
println!("Hello, world!");
let (tx, rx) = flume::unbounded();
thread::spawn(move || {
(0..10).for_each(|i| {
tx.send(i).unwrap();
})
});
let received: u32 = rx.iter().sum();
assert_eq!((0..10).sum::<u32>(), received);
}
std::sync::mpsc 更快,某些情况比 crossbeam-channel 更快unsafe !Sender 和 Receiver 同时支持 Send + Sync + Clonestd::sync::mpsc的用法一致async支持select的接口no_std的全局异步任务spawnertask-stream是一个全局任务spawner,可以在no_std中运行。fn test_sync_fun() {
fn sync_task() {
println!("sync_task.");
}
task_stream::spawn(async {
sync_task();
});
}
fn test_async_fun() {
async fn async_task() {
println!("async_task.");
}
task_stream::spawn(async_task());
}
fn test_capture_var() {
let a: usize = 1;
task_stream::spawn(async move {
println!("catch a: {}.", a);
});
}
fn test_sleep() {
task_stream::spawn(async move {
let mut now: u64 = 0;
loop {
println!("now: {}.", now);
task_stream::sleep(Duration::from_millis(1000)).await;
now += 1000;
}
});
}
let top_permit = permit::Permit::new();
// Start some worker threads.
for _ in 0..5 {
let permit = top_permit.new_sub();
std::thread::spawn(move || {
while !permit.is_revoked() {
// ...
}
});
}
wait_for_shutdown_signal();
// Revoke all thread permits.
top_permit.revoke();
// Give the threads time to finish
// and drop their permits.
let _ = top_permit.try_wait_for(
core::time::Duration::from_secs(3));
gumdrop原文作者:Rust语言中文社区;如有侵权,请联系管理员删除。