0PricingLogin
Learn Rust Coding · Lesson

mpsc Channels

Send between threads.

What Is a Channel?

A channel is a one-way pipe for sending values from one thread to another. Rust's standard library provides std::sync::mpsc where mpsc means multiple producer, single consumer.

  • The Sender half pushes values in.
  • The Receiver half pulls values out.

Channels let threads communicate by passing messages instead of sharing memory directly, which avoids many data races.

Creating a Channel

Call mpsc::channel() to get a tuple of (Sender, Receiver). Here we send one value from a spawned thread back to the main thread.

use std::sync::mpsc;
use std::thread;

fn main() {
    let (tx, rx) = mpsc::channel();
    thread::spawn(move || {
        tx.send(42).unwrap();
    });
    let received = rx.recv().unwrap();
    println!("Got: {}", received);
}

All lessons in this course

  1. mpsc Channels
  2. Sharing State with Arc/Mutex
  3. Scoped Threads
  4. Crossbeam Channels
← Back to Learn Rust Coding