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

相关推荐
姜学迁12 小时前
Rust-枚举
开发语言·后端·rust
凌云行者12 小时前
rust的迭代器方法——collect
开发语言·rust
QMCY_jason18 小时前
Ubuntu 安装RUST
linux·ubuntu·rust
碳苯1 天前
【rCore OS 开源操作系统】Rust 枚举与模式匹配
开发语言·人工智能·后端·rust·操作系统·os
zaim11 天前
计算机的错误计算(一百一十四)
java·c++·python·rust·go·c·多项式
凌云行者1 天前
使用rust写一个Web服务器——单线程版本
服务器·前端·rust
cyz1410012 天前
vue3+vite@4+ts+elementplus创建项目详解
开发语言·后端·rust
超人不怕冷2 天前
[rust]多线程通信之通道
rust
逢生博客2 天前
Rust 语言开发 ESP32C3 并在 Wokwi 电子模拟器上运行(esp-hal 非标准库、LCD1602、I2C)
开发语言·后端·嵌入式硬件·rust
Maer092 天前
WSL (Linux)配置 Rust 开发调试环境
linux·运维·rust