Is a for loop iteration over a receiving end of a mpsc implicitly sleeping?

⚓ rust    📅 2025-06-05    👤 surdeus    👁️ 3      

surdeus

Hello,

I am following the Rust book and have a question on the following code.
I found a question on the topic Iterating through Channel
but the answer does not explain what exactly happens.
How does the for loop iteration know when to wait for another input in rx and when to exit the loop?

use std::sync::mpsc;
use std::thread;
use std::time::Duration;

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

    thread::spawn(move || {
        let vals = vec![
            String::from("hi"),
            String::from("from"),
            String::from("the"),
            String::from("thread"),
        ];

        for val in vals {
            tx.send(val).unwrap();
            thread::sleep(Duration::from_secs(1));
        }
    });

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

3 posts - 3 participants

Read full topic

🏷️ rust_feed