Skip to content
เข้าสู่ระบบ

Sync - ซิงค์ข้อมูลระหว่าง Threads

std::sync module มี primitives สำหรับ share ข้อมูลระหว่าง threads อย่างปลอดภัย รวมถึง mutexes, channels และ atomic types

Module นี้ประกอบด้วย types หลักสำหรับ concurrent programming:

Typeใช้ทำอะไร
Arc<T>แชร์ ownership ระหว่าง threads
Mutex<T>Exclusive access (ทีละ thread)
RwLock<T>หลาย readers หรือ 1 writer
mpscChannels สำหรับส่งข้อมูล
Barrierรอให้ทุก thread มาถึง
CondvarCondition 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 เพื่อปลดล็อกบทความทั้งหมด