Rust 中的 runtime 到底是咋回事, 为了彻底搞懂它, 我在尽量不借助第三方 crate 的情况下实现了一个玩具 runtime, 之所以说是玩具,因为它没有复杂的调度算法(只有一个全局 task queue)
代码除了 mpmc(multi-producer, multi-consumer) 使用第三方 crate crossbeam 之外, 其余代码一律手撸
可以这么玩
fn main() {
let toy = Toy::new();
for i in 1..=20 {
toy.spawn(async move {
let ret = FakeIO::new(Duration::from_secs(i)).await;
println!("{:?}: {:?}", thread::current().id(), ret);
})
}
toy.run(4); // 4 threads
}
其中 FakeIO 也是足够单纯
pub struct FakeIO {
finished: Arc<AtomicBool>,
duration: Duration,
}
impl Future for FakeIO {
type Output = Duration;
fn poll(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Self::Output> {
if self.finished.load(