rust 在 linux 平臺上的并發機制表現得尤為出色,這得益于其標準庫提供的豐富并發原語。以下將介紹一些核心概念及示例代碼,幫助你更好地掌握 Rust 的并發編程技巧。
基礎并發工具
-
線程(Threads): Rust 提供了 std::thread 模塊用于創建和管理線程。
use std::thread; fn main() { let handle = thread::spawn(|| { println!("這是新線程!"); }); handle.join().unwrap(); }
-
共享內存與互斥鎖(Mutex): 利用 Mutex 可以確保多個線程安全地訪問共享資源。
use std::sync::{Arc, Mutex}; use std::thread; fn main() { let counter = Arc::new(Mutex::new(0)); let mut handles = vec![]; for _ in 0..10 { let counter = Arc::clone(&counter); let handle = thread::spawn(move || { let mut num = counter.lock().unwrap(); *num += 1; }); handles.push(handle); } for handle in handles { handle.join().unwrap(); } println!("計數器值: {}", *counter.lock().unwrap()); }
-
線程間通信(Channels): 使用 mpsc 模塊可以實現多生產者單消費者的消息傳遞模式。
use std::sync::mpsc; use std::thread; fn main() { let (tx, rx) = mpsc::channel(); thread::spawn(move || { tx.send("hello").unwrap(); }); let message = rx.recv().unwrap(); println!("Received: {}", message); }
進階并發工具
-
原子操作(Atomic Operations): 利用 std::sync::atomic 模塊執行低級的原子操作。
use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; use std::thread; fn main() { let counter = Arc::new(AtomicUsize::new(0)); let mut handles = vec![]; for _ in 0..10 { let counter = Arc::clone(&counter); let handle = thread::spawn(move || { counter.fetch_add(1, Ordering::SeqCst); }); handles.push(handle); } for handle in handles { handle.join().unwrap(); } println!("計數器值: {}", counter.load(Ordering::SeqCst)); }
-
讀寫鎖(RwLock): 使用 std::sync::RwLock 允許多個讀取線程同時訪問數據,而寫入線程則獨占訪問。
use std::sync::{Arc, RwLock}; use std::thread; fn main() { let data = Arc::new(RwLock::new(0)); let mut handles = vec![]; for i in 0..10 { let data = Arc::clone(&data); let handle = thread::spawn(move || { let mut num = data.write().unwrap(); *num += 1; }); handles.push(handle); } for handle in handles { handle.join().unwrap(); } println!("數據值: {}", *data.read().unwrap()); }
擴展資料
借助上述內容和工具,你可以更輕松地編寫出高效、安全的并發程序。
? 版權聲明
文章版權歸作者所有,未經允許請勿轉載。
THE END