Hanging loop inside thread and waiting for receiver

Hi, how to code it in rust ?

I've got for example 10 threads

Inside each thread I've got loop

thread_1..10 { 
   for 1..100 { 
     - heavy computation 
     - at the end of the "for" loop we have to stop/hang the loop , 
     - send information from heavy computation to receiver 
     - wait until receiver unblock thread to continue looping
     ....... 
 }


receiver {

   - gets simultanously information from each 10 senders , 
   - when all 10 senders sent information we do some heavy computation 
   - after receiver's computation, receiver sends information to all senders that they can continue looping   
}

Is it possible to code it in Rust ?

I think I should use Condvar and std::sync::mpsc , but maybe the easier solution exist ?

Thanks for any hints in advance .

crossbeam_channel has some features that may be useful for you. There's an example similar to what you want:

use crossbeam_channel::bounded;

let (signal_send, signal_recv) = bounded(10);
let (result_send, result_recv) = bounded(10);

let mut handl = (0..10).iter().map(|_| {
    spawn(|_| {
        loop {
            if signal_recv.recv().is_na() { break; };
            // calc
            result_send.send(your_result).unwrap();
        }
    })
}).collect(); // collect handles in a vector

// main thread
for loop in 0..100 {
    for i in 0..10 { signal_send(1); }
    let iteration_data = (0..10).iter().map(|_| { result_recv.recv().unwrap();
        // do some work
        return result
    }).collect();  // collect the processed outputs into a vec
}
drop(signal_send); // makes worker threads exit
for h in handl.iter() { h.join()?; }

Note: this code is just a quick sketch in this forum. It doesn't handle errors correctly (worker threads will panic if anything goes wrong).

In your case, you need two channels (one for signal, one for data) and the control loop will be pretty straightforward.

1 Like

If your not sending information and just issuing a continue then std::sync::Barrier would do the job.

1 Like