Mini-Tokio 的精简实现代码

rust 复制代码
use futures::future::BoxFuture;
use std::future::Future;
use std::sync::{Arc, Mutex};
use std::task::{Context};
use futures::task::{self, ArcWake};
use crossbeam::channel;


struct MiniTokio {
    scheduled: channel::Receiver<Arc<Task>>,
    sender: channel::Sender<Arc<Task>>,
}

impl MiniTokio {
    fn new() -> MiniTokio {
        let (sender, scheduled) = channel::unbounded();
        MiniTokio { scheduled, sender }
    }
    fn spawn<F>(&self, future: F)
        where
            F: Future<Output=()> + Send + 'static,
    {
        Task::spawn(future, &self.sender);
    }
    fn run(&self) {
        while let Ok(task) = self.scheduled.recv() {
            task.poll();
        }
    }
}

struct Task {
    // Pin<Box<dyn Future<Output = T> + Send + 'static>>
    future: Mutex<BoxFuture<'static, ()>>,
    executor: channel::Sender<Arc<Task>>,
}

impl Task {
    fn spawn<F>(future: F, sender: &channel::Sender<Arc<Task>>)
        where
            F: Future<Output=()> + Send + 'static,
    {
        let task = Arc::new(Task {
            future: Mutex::new(Box::pin(future)),
            executor: sender.clone(),
        });

        let _ = sender.send(task);
    }
    fn poll(self: Arc<Self>) {
        let waker = task::waker(self.clone());

        let mut cx = Context::from_waker(&waker);
        println!("{}", "创建waker");
        let mut future = self.future.try_lock().unwrap();
        let _ = future.as_mut().poll(&mut cx);
    }
}

impl ArcWake for Task {
    fn wake_by_ref(arc_self: &Arc<Self>) {
        println!("arcWake");
        let _ = arc_self.executor.send(arc_self.clone());
    }
}
// 调用这个函数进行运行 ok?
pub fn yun_xin() {
    let tokio = MiniTokio::new();

    tokio.spawn(async {   println!("hello,world!");() });

    tokio.run();
}

粗略讲解

Rust粗略讲实现异步运行时_哔哩哔哩_bilibili

相关推荐
勇敢牛牛_2 小时前
【conreg-client】在Rust中使用向Feign一样的远程调用
网络·rust·feign
小杍随笔8 小时前
【Rust模块化进阶:深入解析mod.rs的用法与现代实践(1.94版本)】
开发语言·后端·rust
@atweiwei9 小时前
Tokio 深度解析:Rust 异步运行时与 Go 协程对比指南
服务器·网络·后端·golang·rust·内存·所有权
福大大架构师每日一题10 小时前
2026年3月TIOBE编程语言排行榜,Go语言排名第16,Rust语言排名14。为什么 TIOBE 指数仍然依赖搜索引擎?
开发语言·搜索引擎·rust·tiobe
小杍随笔10 小时前
【Rust可见性控制:pub、pub(crate)、pub(super)实战】
开发语言·后端·rust
Source.Liu12 小时前
【Iced】core库下angle.rs文件分析
rust·iced
Source.Liu13 小时前
【A11】a11lib 库作为外部库接口层的设计理念
rust·iced
鸿乃江边鸟13 小时前
Rust 的 mod(模块) 说明
开发语言·后端·rust
小杍随笔13 小时前
【Rust `lib.rs` 使用方法:模块组织、API导出与最佳实践】
服务器·开发语言·rust
用户8815869109114 小时前
为什么说 Rust 是 C++...
rust