std/thread

std/thread 模組提供了用於建立和管理並行執行緒的高階原語。

概覽

使用方法

import "std/thread.zc"
import "std/io.zc"

fn worker(id: int) {
    println(f"來自 worker {id} 的問候");
}

fn main() {
    // 使用閉包衍生執行緒
    let t = Thread::spawn(|| {
        worker(42);
    }).unwrap();
    
    // 顯式等待完成
    t.join();
}

結構體定義

Thread

代表一個衍生執行緒的句柄。

struct Thread {
    handle: void*;
}

方法

Thread 生命週期

方法簽名說明
spawnThread::spawn(func: fn()) -> Result<Thread>衍生一個執行所提供閉包或函數的新執行緒。
joinjoin(self) -> Result<bool>阻塞目前執行緒,直到衍生的執行緒終止。
detachdetach(self) -> Result<bool>分離執行緒,使其獨立運行。資源在退出程序時自動釋放。
cancelcancel(self) -> Result<bool>向執行緒發送取消請求。

工具函數

函數簽名說明
sleep_mssleep_ms(ms: int)將目前執行緒掛起約 ms 毫秒。