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

相关推荐
skilllite作者1 天前
AI agent 的 Assistant Auto LLM Routing 规划的思考
网络·人工智能·算法·rust·openclaw·agentskills
浪客川2 天前
【百例RUST - 013】泛型
开发语言·后端·rust
穗余2 天前
Rust——println!后面的感叹号什么意思【宏】
开发语言·python·rust
Rust研习社2 天前
Rust 写时克隆智能指针 Cow
后端·rust·编程语言
Je1lyfish2 天前
Haskell 初探
开发语言·笔记·算法·rust·lisp·抽象代数
穗余2 天前
Rust——什么是标量类型,isize / usize 是什么
rust
穗余2 天前
Rust——impl是什么意思
开发语言·后端·rust
代码羊羊2 天前
Rust模式匹配
开发语言·后端·rust
好家伙VCC2 天前
**发散创新:用Rust实现基于RAFT共识算法的轻量级分布式日志系统**在分布式系统中,**一致性协议**是保障数据可靠
java·分布式·python·rust·共识算法