bhylu.com

Advertisements

Rust Channels

Send owned data to one receiver and make completion visible.

How it works

A channel transfers messages between senders and a receiver. The standard-library mpsc channel has multiple-producer, single-consumer semantics. Sending ownership of a value can simplify sharing, but message ordering, shutdown and backpressure still need design. An unbounded channel can accumulate work; bounded channels change producer behaviour and should be selected deliberately.

Run the code

Reviewed with Rust 1.97.0, edition 2024, using the standard library only. Save the complete download as lesson-name.rs in a separate learning folder, compile with rustc --edition=2024 lesson-name.rs and run the resulting program (lesson-name.exe on Windows). Use the actual lesson filename. The final project includes complete Cargo package files; run cargo test --offline and cargo run --offline from that separate package folder. There is no Rust browser runner; PHP, Apache and MySQL are not needed.

This complete example was executed in the stated local review environment.

Download complete source

Example

channels.rs

fn main() {
    use std::sync::mpsc;
    let (sender, receiver) = mpsc::channel();
    let worker = std::thread::spawn(move || { sender.send(8_u32).expect("receiver alive"); });
    let count = receiver.recv().expect("fixture message");
    worker.join().expect("worker complete");
    assert_eq!(count, 8);
    assert!(receiver.recv().is_err());
    println!("Received 8; channel closes after sender exits");
}

Expected result

Received 8; channel closes after sender exits

The sender moves into the worker, sends once and is dropped as the thread exits. After joining, the second receive reports disconnection instead of waiting for a sender that still exists. Real workflows should distinguish an empty channel, a timeout and permanent closure rather than treating them as the same event.

Primary technical reference: Rust documentation.