CodeBlanks Logo Icon CodeBlanks

mpsc channel

Create a channel with std::sync::mpsc.

The mpsc channel

Channels let threads communicate by messages instead of sharing data: "Don't communicate by sharing memory; share memory by communicating." mpsc (multiple producer, single consumer) gives a sender (tx) and a receiver (rx):

use std::sync::mpsc;

let (tx, rx) = mpsc::channel();
thread::spawn(move || {
    for i in 1..=3 {
        tx.send(format!("mesaj {i}")).unwrap();
    }
});
for m in rx {                // the loop ends when tx is dropped
    println!("{m}");
}

Ownership of the sent value passes to the receiver; the sender can no longer access it.

A channel is an iterator

for m in rx (or rx.iter()) calls recv for each message and ends when all senders are dropped. When the sender thread's closure finishes, tx is dropped automatically, so the loop ends on its own.

// message order is preserved for a single sender
// mesaj 1
// mesaj 2
// mesaj 3

Practice Messages

Open a channel. Let a separate thread send the texts mesaj 1, mesaj 2 and mesaj 3; let the main thread print each with for m in rx.

Starter code

main.rs
use std::sync::mpsc;
use std::thread;

fn main() {
    // buraya yaz
}

Sample solution

main.rs
use std::sync::mpsc;
use std::thread;

fn main() {
    let (tx, rx) = mpsc::channel();
    thread::spawn(move || {
        for i in 1..=3 {
            tx.send(format!("mesaj {i}")).unwrap();
        }
    });
    for m in rx {
        println!("{}", m);
    }
}

Expected output

mesaj 1
mesaj 2
mesaj 3

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What happens if you try to use the value after sending (<code>tx.send(s); println!("{s}")</code>)?

  • It works
  • Panic
  • It prints empty text
  • E0382: s was moved into the channel Correct answer

Explanation: The transfer of ownership makes it impossible for two threads to change the same data at once.

2 Open a channel

Question
let (tx, rx) = mpsc::____();
Answer
let (tx, rx) = mpsc::channel();

Explanation: mpsc::channel returns a (sender, receiver) pair.

3 Piece and role

Term Meaning
tx Sender
rx Receiver
tx.send(v) Transfers ownership
for m in rx Until the senders close

All lessons in Advanced