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

相关推荐
guyoung3 小时前
BoxAgnts 工具系统(6)——多 Provider 适配与 Agent 查询循环
rust·agent·ai编程
星栈3 小时前
Rust + Makepad 应用怎么打包发布:Windows、macOS、Linux 全平台交付
前端·rust
MageGojo4 小时前
R-Shell开源项目实战解析:用Rust打造命令行SSH工具,支持连接管理、远程执行、SFTP与MCP
运维·rust·开源项目·命令行工具·ssh客户端·mcp
techdashen5 小时前
Cargo 1.94 开发周期全解析
开发语言·后端·rust
fox_lht6 小时前
15.4.循环和迭代器的性能比较
开发语言·后端·学习·rust
guyoung7 小时前
BoxAgnts 工具系统(5)——WASM 工具开发:从 Hello World 到生产部署
rust·agent·ai编程
星栈8 小时前
写 Makepad Demo 不难,难的是把它写成项目
前端·rust
咸甜适中9 小时前
rust语言学习笔记Trait(十七)Send、Sync(线程间数据所有权)
笔记·学习·rust
javajenius9 小时前
Pixi:用 Rust 重写 Conda 体验的包管理工具
开发语言·其他·rust·conda
laowangpython9 小时前
tokio-rstracing:Rust 可观测性的标准答案
开发语言·后端·其他·rust