Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Shared State

แชร์ข้อมูลระหว่าง threads ด้วย Mutex

Mutex

use std::sync::Mutex;

fn main() {
    let m = Mutex::new(5);

    {
        let mut num = m.lock().unwrap();
        *num = 6;
    } // lock released here

    println!("m = {:?}", m);
}

⚠️ คำเตือน: อันตรายของ Concurrency

  • 🔴 Deadlock - 2 threads รอกันไปมา ไม่มีใครทำงานต่อ
  • 🔴 Data Race - หลาย threads แก้ไขข้อมูลพร้อมกัน
  • 🔴 Poison - Mutex ถูก poison ถ้า thread panic ขณะถือ lock
+---------------------------------------------------------+
|                    Deadlock Example                     |
+---------------------------------------------------------+
|  Thread A: lock(mutex1) -> wait lock(mutex2)             |
|  Thread B: lock(mutex2) -> wait lock(mutex1)             |
|  !! ทั้งสองรอกันตลอดไป!                                  |
+---------------------------------------------------------+

💡 Best Practices

  • ✅ Lock เร็วที่สุด, ปล่อยเร็วที่สุด
  • ✅ Lock ตามลำดับเดียวกันทุก thread
  • ✅ ใช้ try_lock() เพื่อหลีกเลี่ยง deadlock
  • ✅ ใช้ channels แทน shared state เมื่อเป็นไปได้

Arc + Mutex

Arc = Atomic Reference Counting (thread-safe Rc)

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!("Result: {}", *counter.lock().unwrap()); // 10
}

👉 ต่อไป: Sync & Send