Thread Functions
Functions สำหรับ multi-threading ใน Rust ครอบคลุมการ spawn threads, communication ระหว่าง threads, และ synchronization primitives ที่ช่วยให้เขียน concurrent code ได้อย่างปลอดภัย
1. Spawning Threads
Section titled “1. Spawning Threads”thread::spawn() สร้าง OS thread ใหม่และ return JoinHandle สำหรับ wait และ get result
Basic Thread Spawn
Section titled “Basic Thread Spawn”use std::thread;use std::time::Duration;
fn main() { // Spawn a new thread let handle = thread::spawn(|| { for i in 1..5 { println!("Spawned thread: {}", i); thread::sleep(Duration::from_millis(100)); } 42 // Return value });
// Main thread continues concurrently for i in 1..3 { println!("Main thread: {}", i); thread::sleep(Duration::from_millis(150)); }
// Wait for thread and get result let result = handle.join().expect("Thread panicked"); println!("Thread returned: {}", result);}เข้าสู่ระบบเพื่อดูเนื้อหาเต็ม
ยืนยันตัวตนด้วยบัญชี Google เพื่อปลดล็อกบทความทั้งหมด
Login with Google