Concurrency
ในภาษาอื่น การเขียน Multi-thread คือฝันร้าย (Data Race, Deadlock) แต่ใน Rust… Fearless Concurrency! เพราะ Ownership model ช่วยกันไม่ให้เราเขียนโค้ดที่มี Data Race ได้ตั้งแต่ Compile Time
ลองนึกภาพว่า threads เป็นเหมือน “คนงานหลายคน” ที่ทำงานพร้อมกัน Rust ทำให้เราจัดการได้อย่างปลอดภัย!
1. Creating Threads
Section titled “1. Creating Threads”1.1 Basic Thread
Section titled “1.1 Basic Thread”use std::thread;use std::time::Duration;
fn main() { // ============================================ // thread::spawn = สร้าง thread ใหม่ // คืน JoinHandle สำหรับรอ thread เสร็จ // ============================================ let handle = thread::spawn(|| { for i in 1..5 { println!("Thread: {}", i); thread::sleep(Duration::from_millis(1)); } });
// Main thread ทำงานต่อ for i in 1..3 { println!("Main: {}", i); thread::sleep(Duration::from_millis(1)); }
// ============================================ // join() = รอ thread เสร็จ // ============================================ handle.join().unwrap();}เข้าสู่ระบบเพื่อดูเนื้อหาเต็ม
ยืนยันตัวตนด้วยบัญชี Google เพื่อปลดล็อกบทความทั้งหมด
Login with Google