11. เธรด และก้าวต่อไป

ทำหลายอย่างพร้อมกันอย่างปลอดภัย แล้วจะเรียนอะไรต่อ

เธรด: ทำงานพร้อมกัน

use std::thread;
use std::time::Duration;

fn main() {
    let worker = thread::spawn(|| {
        for i in 1..=3 {
            println!("งานเบื้องหลัง {i}");
            thread::sleep(Duration::from_millis(100));
        }
        42   // ค่าที่เธรดคืน
    });

    println!("main ทำอย่างอื่นไปพลาง ๆ");
    let answer = worker.join().unwrap();   // รอให้เธรดเสร็จ
    println!("ได้ {answer}");
}
ในโปรแกรมฟอร์ม งานที่ใช้เวลานาน (ดาวน์โหลด คำนวณหนัก อ่านไฟล์ใหญ่) ควรทำในเธรดแยก ไม่อย่างนั้นหน้าต่างจะค้างจนกว่างานจะเสร็จ

ส่งข้อมูลระหว่างเธรดด้วย channel

use std::sync::mpsc;
use std::thread;

fn main() {
    let (tx, rx) = mpsc::channel();
    for id in 1..=3 {
        let tx = tx.clone();
        thread::spawn(move || {          // move = ย้ายตัวแปรที่ใช้เข้าไปในเธรด
            tx.send(format!("งาน {id} เสร็จ")).unwrap();
        });
    }
    drop(tx);                            // ปิดฝั่งส่งของ main
    for msg in rx {                      // รับจนกว่าทุกฝั่งส่งจะปิด
        println!("{msg}");
    }
}

ใช้ข้อมูลร่วมกันด้วย Arc และ Mutex

use std::sync::{Arc, Mutex};
use std::thread;

fn main() {
    let counter = Arc::new(Mutex::new(0));   // Arc = แชร์ได้หลายเธรด, Mutex = แก้ได้ทีละคน
    let mut handles = vec![];
    for _ in 0..10 {
        let c = Arc::clone(&counter);
        handles.push(thread::spawn(move || {
            *c.lock().unwrap() += 1;
        }));
    }
    for h in handles {
        h.join().unwrap();
    }
    println!("รวม {}", *counter.lock().unwrap());   // 10 เสมอ
}

ถ้าลืมใส่ Mutex แล้วพยายามแก้ค่าจากหลายเธรด Rust จะไม่ยอม build นี่คือสิ่งที่ภาษาอื่นทำไม่ได้: บั๊กแบบ data race ถูกจับตั้งแต่ตอนคอมไพล์ ใน Phai Studio หน้าต่าง Threads (Ctrl+Alt+H) ช่วยดูว่าแต่ละเธรดกำลังทำอะไรตอนดีบัก

ก้าวต่อไป

ฝึกด้วยโปรเจกต์จริง

หัวข้อที่ควรเรียนต่อ

แหล่งเรียนรู้

ขอให้สนุกกับการเขียน Rust ครับ