Sync - ซิงค์ข้อมูลระหว่าง Threads
std::sync module มี primitives สำหรับ share ข้อมูลระหว่าง threads อย่างปลอดภัย รวมถึง mutexes, channels และ atomic types
sync มีอะไร?
Section titled “sync มีอะไร?”Module นี้ประกอบด้วย types หลักสำหรับ concurrent programming:
| Type | ใช้ทำอะไร |
|---|---|
Arc<T> | แชร์ ownership ระหว่าง threads |
Mutex<T> | Exclusive access (ทีละ thread) |
RwLock<T> | หลาย readers หรือ 1 writer |
mpsc | Channels สำหรับส่งข้อมูล |
Barrier | รอให้ทุก thread มาถึง |
Condvar | Condition variable สำหรับ signaling |
use std::sync::{Arc, Mutex};use std::thread;
fn main() { // ============================================ // ทำไมต้อง sync? // ============================================
// Threads share memory แต่ต้อง synchronize access // ไม่งั้นจะเกิด data races
let data = Arc::new(Mutex::new(0)); let mut handles = vec![];
for _ in 0..5 { let data = Arc::clone(&data); handles.push(thread::spawn(move || { let mut num = data.lock().unwrap(); *num += 1; })); }
for h in handles { h.join().unwrap(); }
println!("Result: {}", *data.lock().unwrap());}เข้าสู่ระบบเพื่อดูเนื้อหาเต็ม
ยืนยันตัวตนด้วยบัญชี Google เพื่อปลดล็อกบทความทั้งหมด
Login with Google