RRust By Example
intermediateConcurrency

Channel Basic

Send messages between threads with channels.

Channel Basic

Send messages between threads with channels.

Difficulty

Intermediate

Code

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

fn main() {
    let (tx, rx) = mpsc::channel();

    thread::spawn(move || {
        let messages = vec!["hello", "from", "the", "thread"];
        for msg in messages {
            tx.send(msg).unwrap();
            thread::sleep(std::time::Duration::from_millis(10));
        }
    });

    for received in rx {
        println!("got: {}", received);
    }
}

Explanation

Channels enable message passing between threads.

Key Concepts

  • Read the code carefully and understand the data flow
  • Try modifying the example to see how it changes behavior
  • Run this code in the Rust Playground

Related Topics

Browse more examples in the concurrency category to build a complete understanding of this topic.

Common Compiler Errors in This Topic

Use these error pages as a debugging companion while practicing this example category.

More Concurrency Examples