欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Rust 多線程編程的實(shí)現(xiàn)

 更新時間:2023年12月07日 11:39:32   作者:int8  
在rust中,多線程編程不算困難,但是也需要留心和別的編程語言中不同的地方,本文主要介紹了Rust 多線程編程的實(shí)現(xiàn),感興趣的可以了解一下

一個進(jìn)程一定有一個主線程,主線程之外創(chuàng)建出來的線程稱為子線程
多線程編程,其實(shí)就是在主線程之外創(chuàng)建子線程,讓子線程和主線程并發(fā)運(yùn)行,完成各自的任務(wù)。
Rust語言支持多線程編程。

Rust語言標(biāo)準(zhǔn)庫中的 std::thread 模塊用于多線程編程。
std::thread 提供很很多方法用于創(chuàng)建線程、管理線程和結(jié)束線程。

一、創(chuàng)建線程

使用std::thread::spawn()方法創(chuàng)建一個線程。

pub fn spawn<F, T>(f: F) -> JoinHandle<T>

參數(shù) f 是一個閉包,是線程要執(zhí)行的代碼。

范例

use std::thread; // 導(dǎo)入線程模塊
use std::time::Duration; // 導(dǎo)入時間模塊
fn main() {
     //創(chuàng)建一個新線程
     thread::spawn(|| {
         for i in 1..10 {
             println!("hi number {} from the spawned thread!", i);
             thread::sleep(Duration::from_millis(1));
         }
     });
     // 主線程要執(zhí)行的代碼
     for i in 1..5 {
         println!("hi number {} from the main thread!", i);
         thread::sleep(Duration::from_millis(1));
     }
}
編譯運(yùn)行結(jié)果如下
hi number 1 from the main thread!
hi number 1 from the spawned thread!
hi number 2 from the main thread!
hi number 2 from the spawned thread!
hi number 3 from the main thread!
hi number 3 from the spawned thread!
hi number 4 from the spawned thread!
hi number 4 from the main thread!

咦,執(zhí)行結(jié)果好像出錯了? 是嗎?
當(dāng)主線程執(zhí)行結(jié)束,那么就會自動關(guān)閉創(chuàng)建出來的子線程。
上面的代碼,我們調(diào)用 thread::sleep() 函數(shù)強(qiáng)制線程休眠一段時間,這就允許不同的線程交替執(zhí)行。
雖然某個線程休眠時會自動讓出cpu,但并不保證其它線程會執(zhí)行。這取決于操作系統(tǒng)如何調(diào)度線程。
這個范例的輸出結(jié)果是隨機(jī)的,主線程一旦執(zhí)行完成程序就會自動退出,不會繼續(xù)等待子線程。這就是子線程的輸出結(jié)果不全的原因。

二、讓主線程等待子線程

默認(rèn)情況下,主線程并不會等待子線程執(zhí)行完畢。為了避免這種情況,我們可以讓主線程等待子線程執(zhí)行完畢然后再繼續(xù)執(zhí)行。

Rust標(biāo)準(zhǔn)庫提供了 join() 方法用于把子線程加入主線程等待隊(duì)列。

spawn<F, T>(f: F) -> JoinHandle<T>

范例

use std::thread;
use std::time::Duration;
fn main() {
     let handle = thread::spawn(|| {
         for i in 1..10 {
             println!("hi number {} from the spawned thread!", i);
             thread::sleep(Duration::from_millis(1));
         }
     });
     for i in 1..5 {
         println!("hi number {} from the main thread!", i);
         thread::sleep(Duration::from_millis(1));
     }
     handle.join().unwrap();
}
編譯運(yùn)行結(jié)果如下
hi number 1 from the main thread!
hi number 1 from the spawned thread!
hi number 2 from the spawned thread!
hi number 2 from the main thread!
hi number 3 from the spawned thread!
hi number 3 from the main thread!
hi number 4 from the main thread!
hi number 4 from the spawned thread!
hi number 5 from the spawned thread!
hi number 6 from the spawned thread!
hi number 7 from the spawned thread!
hi number 8 from the spawned thread!
hi number 9 from the spawned thread!

從輸出結(jié)果來看,主線程和子線程交替執(zhí)行。
主線程等待子線程執(zhí)行完畢是因?yàn)檎{(diào)用了 join() 方法。

三、move強(qiáng)制所有權(quán)遷移

這是一個經(jīng)常遇到的情況:
實(shí)例

use std::thread;
fn main() {
    let s = "hello";
   
    let handle = thread::spawn(|| {
        println!("{}", s);
    });

    handle.join().unwrap();
}

在子線程中嘗試使用當(dāng)前函數(shù)的資源,這一定是錯誤的!因?yàn)樗袡?quán)機(jī)制禁止這種危險(xiǎn)情況的產(chǎn)生,它將破壞所有權(quán)機(jī)制銷毀資源的一定性。我們可以使用閉包的move關(guān)鍵字來處理:
實(shí)例

use std::thread;
fn main() {
    let s = "hello";
   
    let handle = thread::spawn(move || {
        println!("{}", s);
    });

    handle.join().unwrap();
}

四、消息傳遞

使用通道傳遞消息,通道有兩部分組成,一個發(fā)送者(transmitter)和一個接收者(receiver)。
std::sync::mpsc包含了消息傳遞的方法:
實(shí)例

use std::thread;
use std::sync::mpsc;
fn main() {
    let (tx, rx) = mpsc::channel();
    thread::spawn(move || {
        let val = String::from("hi");
        tx.send(val).unwrap();
    });
    let received = rx.recv().unwrap();
    println!("Got: {}", received);
}
運(yùn)行結(jié)果:
Got: hi

子線程獲得了主線程的發(fā)送者tx,并調(diào)用了它的send方法發(fā)送了一個字符串,然后主線程就通過對應(yīng)的接收者rx接收到了。

到此這篇關(guān)于Rust 多線程編程的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)Rust 多線程內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Windows系統(tǒng)下安裝Rust環(huán)境超詳細(xì)教程

    Windows系統(tǒng)下安裝Rust環(huán)境超詳細(xì)教程

    這篇文章主要介紹了如何在Windows系統(tǒng)上安裝mingw64和Rust,mingw64是一個輕便的C語言編譯環(huán)境,可以替代Rust默認(rèn)使用的Visual?Studio,文中通過圖文介紹的非常詳細(xì),需要的朋友可以參考下
    2025-02-02
  • Rust中的關(guān)聯(lián)類型總結(jié)

    Rust中的關(guān)聯(lián)類型總結(jié)

    關(guān)聯(lián)類型是定義通用trait的一種機(jī)制。它允許在trait中定義一個或多個占位符類型,這些類型將在trait的實(shí)現(xiàn)中具體化。文中有詳細(xì)示例代碼供參考,需要的朋友可以閱讀一下
    2023-05-05
  • Rust中的內(nèi)部可變性與RefCell<T>詳解

    Rust中的內(nèi)部可變性與RefCell<T>詳解

    內(nèi)部可變性允許在不可變引用中修改內(nèi)部數(shù)據(jù),通過RefCell在運(yùn)行時檢查借用規(guī)則,適用于Mock對象和多所有權(quán)的可變性場景,結(jié)合Rc和RefCell實(shí)現(xiàn)多所有者共享并修改數(shù)據(jù),但僅適用于單線程
    2025-02-02
  • 一步到位,教你如何在Windows成功安裝Rust

    一步到位,教你如何在Windows成功安裝Rust

    一步到位:輕松學(xué)會在Windows上安裝Rust!想快速掌握Rust編程語言?別再為復(fù)雜教程頭疼!這份指南將手把手帶你順利完成Windows平臺上的Rust安裝全過程,從此編碼之旅更加順暢無阻,立即閱讀,開始你的Rust編程旅程吧!
    2024-01-01
  • Rust字符串匹配Rabin-Karp算法詳解

    Rust字符串匹配Rabin-Karp算法詳解

    Rabin-Karp算法也可以叫 Karp-Rabin 算法,它是用來解決多模式串匹配問題的,它的實(shí)現(xiàn)方式有點(diǎn)與眾不同,首先是計(jì)算兩個字符串的哈希值,然后通過比較這兩個哈希值的大小來判斷是否出現(xiàn)匹配,本文詳細(xì)介紹了字符串匹配Rabin-Karp算法,需要的朋友可以參考下
    2023-05-05
  • Rust?編程語言中的所有權(quán)ownership詳解

    Rust?編程語言中的所有權(quán)ownership詳解

    這篇文章主要介紹了Rust?編程語言中的所有權(quán)ownership詳解的相關(guān)資料,需要的朋友可以參考下
    2023-02-02
  • rust將bitmap位圖文件另存為png格式的方法

    rust將bitmap位圖文件另存為png格式的方法

    通過添加依賴,轉(zhuǎn)換函數(shù)和單元測試操作步驟來解決將bitmap位圖文件另存為png格式文件,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對rust bitmap位另存為png格式的操作方法感興趣的朋友一起看看吧
    2024-03-03
  • Rust?連接?PostgreSQL?數(shù)據(jù)庫的詳細(xì)過程

    Rust?連接?PostgreSQL?數(shù)據(jù)庫的詳細(xì)過程

    這篇文章主要介紹了Rust?連接?PostgreSQL?數(shù)據(jù)庫的完整代碼,本文圖文實(shí)例代碼相結(jié)合給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-01-01
  • Rust中::和.的區(qū)別解析

    Rust中::和.的區(qū)別解析

    Rust中的::和.是兩種常用的操作符,分別用于訪問命名空間中的成員和實(shí)例的字段或方法,感興趣的朋友跟隨小編一起看看吧
    2024-11-11
  • rust多樣化錯誤處理(從零學(xué)習(xí))

    rust多樣化錯誤處理(從零學(xué)習(xí))

    一個優(yōu)秀的項(xiàng)目,錯誤處理的優(yōu)雅性是至關(guān)重要的,而rust,anyhow creat是繞不過去的一個,今天我們來研究下,怎么使用它,幫助我們寫出更優(yōu)雅的代碼,有需要的朋友可以借鑒參考下,希望能夠有所幫助
    2023-11-11

最新評論