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 रिव्यू के साथ।

सभी चैलेंज