Chủ đề Rust quan trọng

Rust Channels: mpsc

Send messages from one thread to another instead of sharing memory.

  • Nâng cao
  • Đọc trong 2 phút
  • 1 ví dụ chạy được
Bạn sẽ học được gì
  • mpsc::channel
  • send and receive
  • How a channel closes
Producer to main
  1. 1sender.sendproducer thread
  2. 2channelstep 1, step 2, step 3
  3. 3for message in receivermain thread

A one-way pipe between threads

A channel is a one-way pipe between threads. One side sends values and the other receives them, so threads can work together without sharing memory.

channel returns a sender and a receiver. The producer thread owns the sender and sends three messages. When the thread ends, the sender is dropped and the channel closes, which ends the for loop over the receiver.

Những điểm quan trọng

  1. channel() returns a sender and a receiver.
  2. The receiver can be used in a for loop.
  3. Dropping the sender closes the channel.

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

Rust
Chạy code →
main.rs
use std::sync::mpsc;
use std::thread;

fn main() {
    let (sender, receiver) = mpsc::channel();

    let producer = thread::spawn(move || {
        for step in 1..=3 {
            sender.send(format!("step {step} done")).unwrap();
        }
    }); // sender is dropped here, which closes the channel

    for message in receiver {
        println!("received: {message}");
    }
    producer.join().unwrap();
    println!("all messages received");
}
Lấy nút Run cho ví dụ này Kết quả khi chạy
received: step 1 done
received: step 2 done
received: step 3 done
all messages received

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.

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