Sync Structs
Synchronization primitives ใน Rust สำหรับ safe concurrent access ถึง shared data ระหว่าง threads
1. Mutex
Section titled “1. Mutex”Mutex<T> (mutual exclusion) ให้ exclusive access แก่ thread เดียวในเวลาเดียว
Basic Mutex Usage
Section titled “Basic Mutex Usage”use std::sync::{Mutex, Arc};use std::thread;
fn main() { // Mutex for mutual exclusion let counter = Arc::new(Mutex::new(0)); let mut handles = vec![];
for _ in 0..5 { let counter = Arc::clone(&counter); let handle = thread::spawn(move || { // lock() blocks until acquired let mut num = counter.lock().unwrap(); *num += 1; // MutexGuard drops here, releasing lock }); handles.push(handle); }
for handle in handles { handle.join().unwrap(); }
println!("Counter: {}", *counter.lock().unwrap());}เข้าสู่ระบบเพื่อดูเนื้อหาเต็ม
ยืนยันตัวตนด้วยบัญชี Google เพื่อปลดล็อกบทความทั้งหมด
Login with Google