Rust:Rust Concurrency: Threads and Channels (std::sync::mpsc)
Rust•Concurrency

Rust Concurrency: Threads and Channels (std::sync::mpsc)

Rust type system guarantees fearless concurrency by catching data races at compile time with Send and Sync.

Syntax

use std::thread; let handle = thread::spawn(move || {}); handle.join().unwrap();

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
thread::spawnFunctionSpawns OS thread executing closure.
mpsc::channelFunctionCreates multiple-producer, single-consumer FIFO channel.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing Rust locally:

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

fn main() {
    println!("--- Spawning Concurrent Threads ---");
    let (tx, rx) = mpsc::channel();

    // Spawn 3 concurrent worker threads
    for i in 1..=3 {
        let tx_clone = tx.clone();
        thread::spawn(move || {
            let msg = format!("Worker #{} finished task", i);
            tx_clone.send(msg).unwrap();
        });
    }

    drop(tx); // Close original transmitter

    // Receive messages from channel
    for received in rx {
        println!("-> Channel received: {}", received);
    }
    println!("All concurrent worker threads finished safely!");
}
Expected Output:
--- Spawning Concurrent Threads ---
-> Channel received: Worker #1 finished task
-> Channel received: Worker #2 finished task
-> Channel received: Worker #3 finished task
All concurrent worker threads finished safely!

How It Works: Step-by-Step

  • Lines 6: Creates mpsc channel returning transmitter (tx) and receiver (rx).
  • Lines 9-15: Spawns 3 OS threads using move closures to transfer ownership into thread.
  • Lines 19-21: Iterates through rx until all transmitters are dropped.

Key Concepts

  • Rust ownership rules prevent data races across threads at compile time.
  • mpsc stands for Multi-Producer, Single-Consumer channel.
  • The move keyword transfers ownership of variables into the thread closure.

Common Mistake: Forgetting to drop the original transmitter tx after cloning for workers

rx continues waiting indefinitely for new messages if any tx remains in scope.

❌ Incorrect
// Missing drop(tx) causes receiver loop to hang forever!
✅ Correct
drop(tx); // Clean channel close

Related Rust Tutorials & Compiler

Run and test Rust on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

Rust Online Compiler