Chủ đề Rust quan trọng

Rust Threads: spawn and join

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

  • Nâng cao
  • Đọc trong 2 phút
  • 1 ví dụ chạy được
Bạn sẽ học được gì
  • 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.

Những điểm quan trọng

  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.

Ví dụ Rust chạy được

Rust
Chạy code →
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}");
    }
}
Lấy nút Run cho ví dụ này Kết quả khi chạy
worker 1 summed to 500500
worker 2 summed to 2001000
worker 3 summed to 4501500

Luyện tập

Mở ví dụ trong trình biên dịch online, đổi một giá trị hoặc thêm một dòng, rồi đoán kết quả trước khi chạy. Sau đó cố ý làm code bị lỗi và đọc thông báo của trình biên dịch.

Bạn học xong bài này chưa?

Đánh dấu đã học để theo dõi tiến độ của bạn.

Tiếp theo: Channels →

Luyện tập với thử thách

Áp dụng kiến thức của bài học này để giải một bài toán thực tế. Mỗi thử thách chạy ngay trên trình duyệt, có kiểm thử tức thì và AI nhận xét.

Tất cả thử thách