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

Thread - หลาย Thread

std::thread สำหรับรันโค้ดพร้อมกันหลาย threads ให้ความสามารถในการทำ parallel computing โดย Rust’s ownership system ช่วยป้องกัน data races ตอน compile time

Thread คือ unit of execution ที่รันพร้อมกันได้ใน process เดียวกัน โดย Rust ใช้ native OS threads ซึ่งให้ true parallelism

use std::thread;
fn main() {
// ============================================
// Thread concepts
// ============================================
// Main thread - เริ่มต้นโปรแกรม ถ้าจบ threads อื่นจะถูก kill
// Spawned threads - threads ที่สร้างมา แต่ละตัวมี stack ของตัวเอง
// JoinHandle - handle สำหรับ wait และ get result
let handle = thread::spawn(|| {
println!("Hello from spawned thread!");
});
handle.join().unwrap();
println!("Main thread done");
}

เข้าสู่ระบบเพื่อดูเนื้อหาเต็ม

ยืนยันตัวตนด้วยบัญชี Google เพื่อปลดล็อกบทความทั้งหมด