หัวข้อสำคัญของ Rust

Rust Threads: spawn and join

Run code in parallel with thread::spawn and collect each result with join.

  • ระดับสูง
  • อ่าน 2 นาที
  • ตัวอย่างที่รันได้ 1 ตัวอย่าง
สิ่งที่คุณจะได้เรียนรู้
  • thread::spawn
  • move closures
  • join and return values
Three workers
  1. 1spawn x3threads start
  2. 2sumeach works alone
  3. 3join()wait for each
  4. 4resultsprinted in order

Work that runs at the same time

A thread runs a piece of code at the same time as the rest of the program. thread::spawn starts one and returns a handle that you can use to wait for it.

move gives each thread its own copy of id. The threads may finish in any order, but join waits for each handle in the order they were created, so the output is always the same. join returns the value the closure produced.

ประเด็นสำคัญ

  1. spawn starts a thread and returns a handle.
  2. move gives the thread its own data.
  3. join waits and returns the thread's value.

ตัวอย่าง Rust ที่รันได้

Rust
รันโค้ด →
main.rs
use std::thread;

fn main() {
    let mut handles = Vec::new();

    for id in 1..=3u64 {
        let handle = thread::spawn(move || {
            let total: u64 = (1..=id * 1000).sum();
            (id, total)
        });
        handles.push(handle);
    }

    for handle in handles {
        let (id, total) = handle.join().unwrap();
        println!("worker {id} summed to {total}");
    }
}
สร้างปุ่ม Run สำหรับตัวอย่างนี้ ผลลัพธ์จากการรันโค้ด
worker 1 summed to 500500
worker 2 summed to 2001000
worker 3 summed to 4501500

ฝึกฝน

เปิดตัวอย่างในคอมไพเลอร์ออนไลน์ ลองเปลี่ยนค่าหรือเพิ่มบรรทัด แล้วทายผลลัพธ์ก่อนกดรัน จากนั้นลองทำให้โค้ดผิดโดยตั้งใจ แล้วอ่านข้อความจากคอมไพเลอร์

เรียนบทนี้จบแล้วใช่ไหม

ทำเครื่องหมายว่าเรียนแล้วเพื่อติดตามความคืบหน้า

ถัดไป: Channels →

ฝึกด้วยโจทย์

ใช้สิ่งที่เรียนในบทนี้แก้ปัญหาจริง ทุกโจทย์รันในเบราว์เซอร์ พร้อมการทดสอบทันทีและรีวิวจาก AI

โจทย์ทั้งหมด