Info
This post is auto-generated from RSS feed The Rust Programming Language Forum - Latest topics. Source: Avoiding usage of unwrap() with JoinHandle
A pattern of creating a vec
of std::thread::JoinHandle
s, adding each thread's handle to it during a for loop creation of threads and then join()
ing them at the end with another for loop seems to be quite common, as seen in this stackoverflow question and this example from tiny-http
.
use std::thread;
fn main() {
let mut handles = vec![];
for _ in 0..4 {
let handle = thread::spawn(move || {
todo!();
//DO THINGS
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
println!("Done");
}
All the examples I have found use unwrap()
on the handle.join()
call but I would like to avoid panic
ing in this function (the example above shows calling in the main function but my actual use case is within a non-main function). I am using anyhow
and ?
to deal with returning errors from functions but I get errors about unsized types when attempting to use it with std::thread::Result<T>
.
Looking for any suggestions on handling the result of std::thread::join()
without using unwrap()
, or reasons why it is not possible.
Thanks
Note: I did find std::thread::scope
in one of the suggested threads while writing this post and may go that way, but I am still interested in learning if handing the result of std::thread::join()
is possible without using unwrap()
.
12 posts - 4 participants
🏷️ rust_feed