Multi_threads: of one thread, is it possible to return a middle result before it has been done?

I have a main function in which 10 seperate threads were generated and each thread structure is as below:

start
...
// here I want to return a 'result' to main funciton before this thread is completed.
...
end

You could use an mpsc channel to send a result of whatever the first half of the thread code has produced back to the main thread. See here : Using Message Passing to Transfer Data Between Threads - The Rust Programming Language

In you main thread you can use select! to get the results from all your threads:std::select! - Rust

Having done that it might be better to send the final results of your threads to main via those channels than to have them return the results when they complete.

1 Like

Wasn't able to find this is actual std documentation, are you sure it's still there?

1 Like

Ah, sorry. You are right. I don't think std has select! anymore.

I'm actually using crossbeam channels: crossbeam::channel - Rust

use crossbeam_channel::{select, unbounded, Receiver, RecvError, Sender, TryRecvError};

// Creating channels:
let (a_tx, a_rx): (Sender<String>, Receiver<String>) = unbounded();
let (b_tx, b_rx): (Sender<String>, Receiver<String>) = unbounded();
...
...
// In the threads we do:
a_tx.send(msg)?;
...
...
// and
b_tx.send(msg)?;
...
...
// In the main thread we do:
    loop {
        // At most one of these two receive operations will be executed.
        select! {
                recv(a_rx) -> msg => {
                    match msg {
                        Ok(msg) => { /* Handle messages from a */ },
                        Err(e) => { /* Handle errors */ }
                    }
                },
                recv(b_rx) -> msg => {
                    match msg {
                        Ok(msg) => { /* Handle messages from b */ },
                        Err(e) => { /* Handle errors */ }
                    }
                },
                default(Duration::from_secs(10)) => { /* Handle the out */ },
            }
    }

Also, while we do not return any values as results from threads anymore we do return Result<()> from threads to pick up any errors.

1 Like