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

Thread Structs

Thread management types ใน Rust ให้เครื่องมือครบครันสำหรับ concurrent programming โดยมี safety guarantees จาก type system ทำให้หลีกเลี่ยง data races ได้ตั้งแต่ compile time

หัวข้อหลัก: Thread Basics

Section titled “หัวข้อหลัก: Thread Basics”

การสร้างและจัดการ threads เป็นพื้นฐานของ concurrent programming โดย Rust ใช้ OS threads และมี wrapper types ที่ปลอดภัย

thread::spawn เป็นวิธีหลักในการสร้าง thread ใหม่ โดยรับ closure ที่จะ run ใน thread นั้น

use std::thread;
fn main() {
println!("=== thread::spawn ===\n");
// Basic thread spawn
let handle = thread::spawn(|| {
println!("Hello from spawned thread!");
42
});
// Wait for completion and get result
let result = handle.join().unwrap();
println!("Thread returned: {}", result);
// With move closure
let data = vec![1, 2, 3];
let handle = thread::spawn(move || {
// data is moved here
println!("Data in thread: {:?}", data);
data.iter().sum::<i32>()
});
let sum = handle.join().unwrap();
println!("Sum: {}", sum);
}

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

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