rust異步編程詳細(xì)講解
簡(jiǎn)化版本 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 任務(wù),Ready 執(zhí)行完成, pending 阻塞 執(zhí)行其他任務(wù) reactor 檢查任務(wù)是否變成 ready
simpleFuture 是一個(gè)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)技術(shù) struct MySleeper { polls: u64, wake: u32, // 簡(jiǎn)化使用整數(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> { // 簡(jiǎn)化編程 使用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, } } // 知道哪個(gè)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)進(jì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) 每隔一秒鐘檢測(cè)一下 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); }
在簡(jiǎn)化版本的Future 對(duì)象中 有定義MyReactor, 和 MyExecutor, MyReactor wake 函數(shù)進(jìn)行標(biāo)記后調(diào)用自定義的check_staus 模擬Future的就緒,調(diào)用wake 函數(shù)通知, 在MyExector 的block_on 函數(shù)中 通過wake函數(shù)匹配狀態(tài) 判讀任務(wù)是否已經(jīng)Ready
理解Future的模型
運(yùn)行時(shí)狀態(tài)的框架: async-std, futures 中已經(jīng)實(shí)現(xiàn)executor不需要自己在實(shí)現(xiàn)。
異步編程中,rust的編程語言中只給我們提供trait Future, async-std, tokio,futures 等異步編程庫(kù) 對(duì)其進(jìn)行擴(kuò)展,并且提供相對(duì)應(yīng)的函數(shù)
async fn hello() { println!("hello"); } 等價(jià)于下面函數(shù) fn hello() -> impl Future<Output=()> { async { println!("hello"); } }
rust 標(biāo)準(zhǔn)庫(kù)中 Future如下:
pub trait Future { type Output; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>; } // Pin 可以創(chuàng)建不可移動(dòng)Future,通過不可移動(dòng)對(duì)象在他們字段中存儲(chǔ)指針 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ù)的版本中會(huì)支持 異步閉包 ##### async lifetime ```rust 這個(gè)函數(shù)的生命周期 // fn foo_expand(x: &'a u8) -> impl Future<Output = u8> + 'a { // async { // *x // } // } async fn foo(x: & u8) -> u8 { *x } // async 函數(shù)返回一個(gè)Future的對(duì)象 fn good() -> impl Future<Output = u8>{ // 異步代碼塊中,定義 變量后 調(diào)用foo_expand async 函數(shù)后進(jìn)行await async { // x 修飾后 x 的生命周期有多長(zhǎng) 就有多長(zhǎng) let x = 5; foo_expand(&x).await } }
到此這篇關(guān)于rust異步編程詳細(xì)講解的文章就介紹到這了,更多相關(guān)rust異步編程內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
前端基于Rust實(shí)現(xiàn)的Wasm進(jìn)行圖片壓縮的技術(shù)文檔(實(shí)現(xiàn)方案)
在現(xiàn)代Web開發(fā)中,利用Rust編寫的圖片壓縮代碼可以編譯成WebAssembly(Wasm)模塊,Rust的內(nèi)存安全特性和Wasm的跨平臺(tái)能力,使得這種方案既高效又安全,對(duì)Rust?Wasm圖片壓縮實(shí)現(xiàn)方案感興趣的朋友一起看看吧2024-09-09Rust語言從入門到精通系列之Iterator迭代器深入詳解
這篇文章主要為大家介紹了Rust語言從入門到精通系列之Iterator迭代器深入詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-04-04Rust 數(shù)據(jù)分析利器polars用法詳解
這篇文章主要介紹了Rust 數(shù)據(jù)分析利器polars用法詳解,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧2024-08-08Rust生命周期常見誤區(qū)(中英對(duì)照)全面指南
這篇文章主要WEIDJAI?介紹了Rust生命周期常見誤區(qū)(中英對(duì)照)的全面指南,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-11-11Rust語言之Prometheus系統(tǒng)監(jiān)控工具包的使用詳解
Prometheus?是一個(gè)開源的系統(tǒng)監(jiān)控和警報(bào)工具包,最初是由SoundCloud構(gòu)建的,隨著時(shí)間的發(fā)展,Prometheus已經(jīng)具有適用于各種使用場(chǎng)景的版本,為了開發(fā)者方便開發(fā),更是有各種語言版本的Prometheus的開發(fā)工具包,本文主要介紹Rust版本的Prometheus開發(fā)工具包2023-10-10