Checking if a channel has messages before temrinating

Hi,

I am currently working with multithreading and I am using a sync channel for message passing between my threads.

When all the senders go out of scope, the receiver terminates before completing the computation.

Is there any way that I can make sure that the messages in the queue are computed before the receiver terminates?

I am looking for any way or method to check if a sync channel has any messages left in it.

Thanks

Channels already handle this, by default. The receiver will not fail when senders go out of scope if there are pending messages. It will keep the messages, and return "disconnected" error only after you receive all pending messages.

1 Like

Here's an example where the sender is dropped before any receives are attempted

Playground

fn main() {
    let rx = {
        let (tx, rx) = std::sync::mpsc::sync_channel(10);

        for value in 0..10 {
            tx.send(value).unwrap();
        }
        
        rx
    };

    loop {
        let value = rx.recv();

        println!("{value:?}");

        if value.is_err() {
            break;
        }
    }
}

Output:

Ok(0)
Ok(1)
Ok(2)
Ok(3)
Ok(4)
Ok(5)
Ok(6)
Ok(7)
Ok(8)
Ok(9)
Err(RecvError)
1 Like

When main() returns, the process is terminated, aborting all child threads. Are you joining the child threads in main before returning?

2 Likes