偷偷摘套内射激情视频,久久精品99国产国产精,中文字幕无线乱码人妻,中文在线中文a,性爽19p

我們一起聊聊如何編寫異步運行時通用庫?

開發(fā) 前端
在Cargo.toml中,你可以簡單地將common-async-runtime作為依賴項包含進來。這使得你的庫代碼很“純粹”,因為現(xiàn)在選擇異步運行時是由下游控制的。與方法1類似,這個crate可以在沒有任何異步運行時的情況下編譯,這很簡潔!?

如果你正在用Rust編寫異步應(yīng)用程序,在某些情況下,你可能希望將代碼分成幾個子crate。這樣做的好處是:

  • 更好的封裝,在子系統(tǒng)之間有一個crate邊界,可以產(chǎn)生更清晰的代碼和定義更良好的API。不再需要這樣寫:pub(crate)。
  • 更快的編譯,通過將一個大crate分解成幾個獨立的小crate,它們可以并發(fā)地編譯。

使用一個異步運行時,編寫異步運行時通用庫的好處是什么?

  • 可移植性,你可以很容易地切換到不同的異步運行時或wasm。
  • 保證正確性,針對tokio和async-std,測試一個庫就可以發(fā)現(xiàn)更多的bug,包括并發(fā)bug(由于任務(wù)執(zhí)行順序模糊)和“未定義行為”(由于誤解異步運行時實現(xiàn)細(xì)節(jié))

下面使用三種方法來實現(xiàn)異步運行時通用庫。

方法1,定義自己的異步運行時Trait

使用futures crate,可以編寫非常通用的庫代碼,但是time,sleep或timeout等操作必須依賴于異步運行時。這時,你可以定義自己的AsyncRuntime trait,并要求下游實現(xiàn)它。

use std::{future::Future, time::Duration};

pub trait AsyncRuntime: Send + Sync + 'static {
    type Delay: Future<Output = ()> + Send;

    // 返回值必須是一個Future
    fn sleep(duration: Duration) -> Self::Delay;
}

可以像這樣使用上面的庫代碼:

async fn operation<R: AsyncRuntime>() {
    R::sleep(Duration::from_millis(1)).await;
}

下面是它如何實現(xiàn)的:

pub struct TokioRuntime;

impl AsyncRuntime for TokioRuntime {
    type Delay = tokio::time::Sleep;

    fn sleep(duration: Duration) -> Self::Delay {
        tokio::time::sleep(duration)
    }
}

#[tokio::main]
async fn main() {
    operation::<TokioRuntime>().await;
    println!("Hello, world!");
}

方法2,在內(nèi)部抽象異步運行時并公開特性標(biāo)志

為了處理網(wǎng)絡(luò)連接或文件句柄,我們可以使用AsyncRead / AsyncWrite trait:

#[async_trait]
pub(crate) trait AsyncRuntime: Send + Sync + 'static {
    type Connection: AsyncRead + AsyncWrite + Send + Sync + 'static;

    async fn connect(addr: SocketAddr) -> std::io::Result<Self::Connection>;
}

可以像這樣使用上面的庫代碼:

async fn operation<R: AsyncRuntime>(conn: &mut R::Connection) 
where
    R::Connection: Unpin,
{
    conn.write(b"some bytes").await;
}

然后為每個異步運行時定義一個模塊:

#[cfg(feature = "runtime-async-std")]
mod async_std_impl;
#[cfg(feature = "runtime-async-std")]
use async_std_impl::*;

#[cfg(feature = "runtime-tokio")]
mod tokio_impl;
#[cfg(feature = "runtime-tokio")]
use tokio_impl::*;

tokio_impl模塊:

mod tokio_impl {
    use std::net::SocketAddr;

    use async_trait::async_trait;
    use crate::AsyncRuntime;

    pub struct TokioRuntime;

    #[async_trait]
    impl AsyncRuntime for TokioRuntime {
        type Connection = tokio::net::TcpStream;

        async fn connect(addr: SocketAddr) -> std::io::Result<Self::Connection> {
            tokio::net::TcpStream::connect(addr).await
        }
    }
}

main函數(shù)代碼:

#[tokio::main]
async fn main() {
    let mut conn =
        TokioRuntime::connect(SocketAddr::new(IpAddr::from_str("0.0.0.0").unwrap(), 8080))
            .await
            .unwrap();
    operation::<TokioRuntime>(&mut conn).await;
    println!("Hello, world!");
}

方法3,維護一個異步運行時抽象庫

基本上,將使用的所有異步運行時api寫成一個包裝器庫。這樣做可能很繁瑣,但也有一個好處,即可以在一個地方為項目指定與異步運行時的所有交互,這對于調(diào)試或跟蹤非常方便。

例如,我們定義異步運行時抽象庫的名字為:common-async-runtime,它的異步任務(wù)處理代碼如下:

// common-async-runtime/tokio_task.rs

pub use tokio::task::{JoinHandle as TaskHandle};

pub fn spawn_task<F, T>(future: F) -> TaskHandle<T>
where
    F: Future<Output = T> + Send + 'static,
    T: Send + 'static,
{
    tokio::task::spawn(future)
}

async-std的任務(wù)API與Tokio略有不同,這需要一些樣板文件:

// common-async-runtime/async_std_task.rs

pub struct TaskHandle<T>(async_std::task::JoinHandle<T>);

pub fn spawn_task<F, T>(future: F) -> TaskHandle<T>
where
    F: Future<Output = T> + Send + 'static,
    T: Send + 'static,
{
    TaskHandle(async_std::task::spawn(future))
}

#[derive(Debug)]
pub struct JoinError;

impl std::error::Error for JoinError {}

impl<T> Future for TaskHandle<T> {
    type Output = Result<T, JoinError>;

    fn poll(
        mut self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Self::Output> {
        match self.0.poll_unpin(cx) {
            std::task::Poll::Ready(res) => std::task::Poll::Ready(Ok(res)),
            std::task::Poll::Pending => std::task::Poll::Pending,
        }
    }
}

在Cargo.toml中,你可以簡單地將common-async-runtime作為依賴項包含進來。這使得你的庫代碼很“純粹”,因為現(xiàn)在選擇異步運行時是由下游控制的。與方法1類似,這個crate可以在沒有任何異步運行時的情況下編譯,這很簡潔!

責(zé)任編輯:武曉燕 來源: coding到燈火闌珊
相關(guān)推薦

2024-09-09 00:00:00

編寫技術(shù)文檔

2025-01-09 07:54:03

2023-11-29 07:10:50

python協(xié)程異步編程

2021-08-27 07:06:10

IOJava抽象

2024-02-20 21:34:16

循環(huán)GolangGo

2023-08-10 08:28:46

網(wǎng)絡(luò)編程通信

2023-08-04 08:20:56

DockerfileDocker工具

2023-06-30 08:18:51

敏捷開發(fā)模式

2023-09-10 21:42:31

2022-05-24 08:21:16

數(shù)據(jù)安全API

2023-04-03 00:09:13

2024-09-30 09:33:31

2024-11-27 16:07:45

2023-07-04 08:06:40

數(shù)據(jù)庫容器公有云

2022-12-05 09:10:21

2024-07-03 08:36:14

序列化算法設(shè)計模式

2022-11-12 12:33:38

CSS預(yù)處理器Sass

2025-03-27 02:00:00

SPIJava接口

2024-02-26 00:00:00

Go性能工具

2023-12-28 09:55:08

隊列數(shù)據(jù)結(jié)構(gòu)存儲
點贊
收藏

51CTO技術(shù)棧公眾號