Waiting for several threads at once

Let's say I have code like this:

    let first_thread = thread::spawn(move || {
        // Do some work that might panic and otherwise never returns
    });


    let second_thread = thread::spawn(move || {
        // Do some work that might panic and otherwise never returns
    });

    if let Err(e) = first_thread.join() {
        println!("{}", e);
    }


    if let Err(e) = second_thread.join() {
        println!("{}", e);
    }

In the case where second_thread panics but first_thread does not, is there a way using Rust's standard threading to be aware that this has happened? Or do I have to use some threadpool to achieve this?

More generally this is something I think about wanting to do a lot, having two or more sources of information and wanting to block on both of them at the same time and once one of them returns I want to continue execution. Is this only achievable with futures or is there another way?

.join is blocking, so you can't use it. You could try using mpsc queue to receive notifications from either thread.

But if you don't actually have to manage threads yourself, use rayon instead. It has scope feature that automatically waits for arbitrary number of async tasks.

I tried googling for mpsc queue but I can't find any mention of a queue in mpsc. Do you have a link to it?

From a quick look at rayon it seems it is supposed to be used for more computation-heavy threads with work-stealing? The threads I have are more io-bound and spend most of their time blocking for a new event and then blocking again (which of course is what async programming is meant to solve but unfortunately there is no time for a complete re-write right now).

The mpsc channel can be found in std::sync::mpsc.

Ah ok, I thought @kornel was referring to a thread queue in mpsc.

I mean a channel is a sort of queue.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.