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

Rust 多線程編程的實現

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

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

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

一、創(chuàng)建線程

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

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

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

范例

use std::thread; // 導入線程模塊
use std::time::Duration; // 導入時間模塊
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));
     }
}
編譯運行結果如下
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í)行結果好像出錯了? 是嗎?
當主線程執(zhí)行結束,那么就會自動關閉創(chuàng)建出來的子線程。
上面的代碼,我們調用 thread::sleep() 函數強制線程休眠一段時間,這就允許不同的線程交替執(zhí)行。
雖然某個線程休眠時會自動讓出cpu,但并不保證其它線程會執(zhí)行。這取決于操作系統(tǒng)如何調度線程。
這個范例的輸出結果是隨機的,主線程一旦執(zhí)行完成程序就會自動退出,不會繼續(xù)等待子線程。這就是子線程的輸出結果不全的原因。

二、讓主線程等待子線程

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

Rust標準庫提供了 join() 方法用于把子線程加入主線程等待隊列。

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();
}
編譯運行結果如下
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!

從輸出結果來看,主線程和子線程交替執(zhí)行。
主線程等待子線程執(zhí)行完畢是因為調用了 join() 方法。

三、move強制所有權遷移

這是一個經常遇到的情況:
實例

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

    handle.join().unwrap();
}

在子線程中嘗試使用當前函數的資源,這一定是錯誤的!因為所有權機制禁止這種危險情況的產生,它將破壞所有權機制銷毀資源的一定性。我們可以使用閉包的move關鍵字來處理:
實例

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

    handle.join().unwrap();
}

四、消息傳遞

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

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);
}
運行結果:
Got: hi

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

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

相關文章

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

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

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

    Rust中的關聯類型總結

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

    Rust中的內部可變性與RefCell<T>詳解

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

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

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

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

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

    Rust?編程語言中的所有權ownership詳解

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

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

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

    Rust?連接?PostgreSQL?數據庫的詳細過程

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

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

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

    rust多樣化錯誤處理(從零學習)

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

最新評論