Unwrapping thread index

    rayon::spawn(move || {
        (1..=rayon::current_num_threads())
            .into_par_iter()
            .for_each(|_| {
                let result = acme(stuff);
                let idx = rayon::current_thread_index().unwrap();
                let _ = tx.send((idx, result));
            });
    });

Should one really call match or if let for current_thread_index()? Because without spawn the index would not exist, would it? The program would fail even before querying the index.

Because without spawn the index would not exist, would it?

Yes, but that's never the case in your code, so there's not much point in handling it. Using unwrap/expect in that scenario is totally fine, imo.

Where matching on it could be useful is if you have code that may or may not be running from a Rayon thread, and you need to do something different based on that.

2 Likes

According to the rayon docs, the return value is guaranteed to be Some(_) when called within a rayon worker thread. Hence, unwrapping within such a thread is fine, though I always prefer expect() over unwrap().

Edit: ninja'd

1 Like

Unfortunately two solutions aren’t possible. Thanks.

Thanks.