rust異步編程詳細講解
簡化版本 Future
// wake 函數(shù) reactor發(fā)現(xiàn)狀態(tài)是ready 通知executor 函數(shù)
trait SimpleFuture {
type Output;
fn poll(&mut self, wake: fn()) -> Poll<Self::Output>;
// fn poll(&mut self, wake: u32) -> Poll<Self::Output>;
}
enum Poll<T> {
Ready(T),
Pending,
}
future 返回的是Poll枚舉 , 狀態(tài)有Ready ,pending 狀態(tài)
executor 調(diào)用 Future 任務,Ready 執(zhí)行完成, pending 阻塞 執(zhí)行其他任務
reactor 檢查任務是否變成 ready
simpleFuture 是一個trait, 屬于struct MySleep
use std::thread;
use std::time::Duration;
trait SimpleFuture {
type Output;
// fn poll(&mut self, wake: fn()) -> Poll<Self::Output>;
fn poll(&mut self, wake: u32) -> Poll<Self::Output>;
}
enum Poll<T> {
Ready(T),
Pending,
}
// 自定義循環(huán)技術
struct MySleeper {
polls: u64,
wake: u32, // 簡化使用整數(shù) 替換函數(shù)
}
impl MySleeper {
fn new(wake: u32) -> Self {
MySleeper {
polls: 0,
wake: wake,
}
}
}
static mut FINISHED: bool = false;
impl SimpleFuture for MySleeper {
type Output = ();
fn poll(&mut self, wake: u32) -> Poll<Self::Output> {
// 簡化編程 使用unsafe 使用外部的變量
unsafe {
if FINISHED {
Poll::Ready(())
} else {
self.wake = wake;
self.polls += 1;
println!("polls = {}", self.polls);
Poll::Pending
}
}
}
}
// 定義自定義Reactor
struct MyReactor {
wake: u32,
// 通知exector
handle: Option<thread::JoinHandle<()>>, // 線程句柄
}
impl MyReactor {
fn new() -> Self {
MyReactor {
wake: 0,
handle: None,
}
}
// 知道哪個wake 通知具體函數(shù)
fn add_wake(&mut self, wake: u32) {
self.wake = wake;
}
// check status
fn check_status(&mut self) {
if self.handle.is_none() {
let wake = self.wake;
// 模擬 通過死循環(huán)進行監(jiān)控狀態(tài)
let handle = thread::spawn(|| loop {
thread::sleep(Duration::from_secs(5));
unsafe {
//模擬future就緒,然后調(diào)用wake
FINISHED = true;
}
});
self.handle = Some(handle);
}
}
}
struct MyExecutor;
impl MyExecutor {
fn block_on<F: SimpleFuture>(mut myfuture: F, wake: u32) {
//阻塞執(zhí)行future
loop {
match myfuture.poll(wake) {
Poll::Ready(_) => {
println!("my future is ok");
break;
}
Poll::Pending => unsafe {
while !FINISHED {
// 循環(huán) 每隔一秒鐘檢測一下
thread::sleep(Duration::from_secs(1));
}
}
}
}
}
}
fn main() {
let mut reactor = MyReactor::new();
let sleeper = MySleeper::new(5);
let wake = sleeper.wake;
reactor.add_wake(wake);
reactor.check_status();
MyExecutor::block_on(sleeper, wake);
}在簡化版本的Future 對象中 有定義MyReactor, 和 MyExecutor, MyReactor wake 函數(shù)進行標記后調(diào)用自定義的check_staus 模擬Future的就緒,調(diào)用wake 函數(shù)通知, 在MyExector 的block_on 函數(shù)中 通過wake函數(shù)匹配狀態(tài) 判讀任務是否已經(jīng)Ready
理解Future的模型
運行時狀態(tài)的框架: async-std, futures 中已經(jīng)實現(xiàn)executor不需要自己在實現(xiàn)。
異步編程中,rust的編程語言中只給我們提供trait Future, async-std, tokio,futures 等異步編程庫 對其進行擴展,并且提供相對應的函數(shù)
async fn hello() {
println!("hello");
}
等價于下面函數(shù)
fn hello() -> impl Future<Output=()> {
async {
println!("hello");
}
}rust 標準庫中 Future如下:
pub trait Future {
type Output;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>;
}
// Pin 可以創(chuàng)建不可移動Future,通過不可移動對象在他們字段中存儲指針
struct MyFut {
a: i32,
ptr: *const i32, // 指針指向字段a 所在的內(nèi)存首地址
}async/awit 使用
在閉包中使用async
use std::future::Future;
fn my_function() -> impl Future<Output = u8> {
let closure = async |x: u8| {
x
};
closure(5)
}
閉包在穩(wěn)定版本還不支持,后續(xù)的版本中會支持 異步閉包
##### async lifetime
```rust
這個函數(shù)的生命周期
// fn foo_expand(x: &'a u8) -> impl Future<Output = u8> + 'a {
// async {
// *x
// }
// }
async fn foo(x: & u8) -> u8 {
*x
}
// async 函數(shù)返回一個Future的對象
fn good() -> impl Future<Output = u8>{
// 異步代碼塊中,定義 變量后 調(diào)用foo_expand async 函數(shù)后進行await
async {
// x 修飾后 x 的生命周期有多長 就有多長
let x = 5;
foo_expand(&x).await
}
}
到此這篇關于rust異步編程詳細講解的文章就介紹到這了,更多相關rust異步編程內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
前端基于Rust實現(xiàn)的Wasm進行圖片壓縮的技術文檔(實現(xiàn)方案)
在現(xiàn)代Web開發(fā)中,利用Rust編寫的圖片壓縮代碼可以編譯成WebAssembly(Wasm)模塊,Rust的內(nèi)存安全特性和Wasm的跨平臺能力,使得這種方案既高效又安全,對Rust?Wasm圖片壓縮實現(xiàn)方案感興趣的朋友一起看看吧2024-09-09
Rust語言從入門到精通系列之Iterator迭代器深入詳解
這篇文章主要為大家介紹了Rust語言從入門到精通系列之Iterator迭代器深入詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-04-04
Rust 數(shù)據(jù)分析利器polars用法詳解
這篇文章主要介紹了Rust 數(shù)據(jù)分析利器polars用法詳解,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友參考下吧2024-08-08
Rust語言之Prometheus系統(tǒng)監(jiān)控工具包的使用詳解
Prometheus?是一個開源的系統(tǒng)監(jiān)控和警報工具包,最初是由SoundCloud構建的,隨著時間的發(fā)展,Prometheus已經(jīng)具有適用于各種使用場景的版本,為了開發(fā)者方便開發(fā),更是有各種語言版本的Prometheus的開發(fā)工具包,本文主要介紹Rust版本的Prometheus開發(fā)工具包2023-10-10

