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

Rust Channels: mpsc

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

  • ระดับสูง
  • อ่าน 2 นาที
  • ตัวอย่างที่รันได้ 1 ตัวอย่าง
สิ่งที่คุณจะได้เรียนรู้
  • 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.

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

  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.

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

Rust
รันโค้ด →
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");
}
สร้างปุ่ม Run สำหรับตัวอย่างนี้ ผลลัพธ์จากการรันโค้ด
received: step 1 done
received: step 2 done
received: step 3 done
all messages received

ฝึกฝน

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

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

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

ถัดไป: Shared State with Arc and Mutex →

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

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

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