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

相关推荐
对象存储与RustFS1 小时前
JuiceFS + 对象存储:把 S3 变成 POSIX 文件系统实测
后端·rust·开源
遇码3 小时前
侧边栏一开,AI 画的东西就被挡住了:给白板画布加「真实可见区」计算和相机补偿
人工智能·ai·rust
geovindu5 小时前
rust: Borg Pattern(续)
开发语言·后端·设计模式·rust·博格模式
轻舟技术A21 小时前
Pi 的 Rust 实现来了:rpi,不止一个终端 Agent
开发语言·后端·rust
wflynn1 天前
GitHub 今日推荐|wordcraft:用 Rust 重写 Word 内核并开放给 AI 调用
rust·开源·github
I'm Jie1 天前
【开源】7 天,我用 Rust 复刻了 FinalShell!Rhost v1.0.0 发布
开发语言·rust·开源
小灰灰搞电子1 天前
Rust+Slint 实现一个终端软件源码分享(半成品)
开发语言·rust
恋喵大鲤鱼1 天前
Rust str 与 String 类型的区别
rust
miofly1 天前
GitHub 今日推荐|fsearch:Rust 打造 macOS 毫秒级全盘文件名与内容搜索工具
rust·开源·github
大鹏的NLP博客1 天前
Rust 的本质:用数学约束实现编译期内存安全
安全·rust