Mini-Tokio 的精简实现代码

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

相关推荐

  1. Mini-Tokio 精简实现代码

    2024-02-20 23:46:03       67 阅读
  2. Rust 实战练习 - 11. Rust异步基石 tokio

    2024-02-20 23:46:03       29 阅读
  3. Tokio强大Rust异步框架

    2024-02-20 23:46:03       35 阅读
  4. rust语言tokio库spawn, blocking_spawn等使用

    2024-02-20 23:46:03       59 阅读
  5. Minio工具类实现(封装了基础minio方法)

    2024-02-20 23:46:03       61 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-02-20 23:46:03       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-02-20 23:46:03       100 阅读
  3. 在Django里面运行非项目文件

    2024-02-20 23:46:03       82 阅读
  4. Python语言-面向对象

    2024-02-20 23:46:03       91 阅读

热门阅读

  1. redis

    2024-02-20 23:46:03       43 阅读
  2. Python系列(17)—— 位运算符

    2024-02-20 23:46:03       44 阅读
  3. MySQL学习笔记4 DQL

    2024-02-20 23:46:03       44 阅读
  4. LeetCode 2744.最大字符串配对数目

    2024-02-20 23:46:03       46 阅读
  5. 什么是机器学习

    2024-02-20 23:46:03       57 阅读
  6. PS的常用快捷方式有哪些?

    2024-02-20 23:46:03       53 阅读
  7. GET变量与POST变量

    2024-02-20 23:46:03       57 阅读