Processing thread results in order they complete

In this simple example of using threads each thread runs for a different amount of time, but I'd like to process the results as each thread completes rather than in the order in which the threads were created. Currently it gets the results in the order the threads were created due to the way I'm using handle.join.
I see that one way I could achieve what I want is to have the threads send their result to the main thread using a channel. Is that the best approarch?

Your issue was that you kept a sender, so the receiver never ended Rust Playground since one sender (the original one as it happens) was never dropped.

In the later loop, of course you're iterating and waiting on each thread in the order it was pushed to the vec. So you're getting each thread result in the order you started them.

1 Like

I see how this allows the for handle loop to begin before the for msg loop exits which is good, But it's still the case that the handle.join calls execute in the order in which the threads where started. What are my options for being able to use the result from each spawned thread as the the threads complete instead of using the results in the order in which the threads were started? Is using channels instead of join the best way to achieve that?

Personally I would go with the channels solution.

1 Like

You could do something like this ? Rust Playground I'm not a big fan of it.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.