Re:Things you can’t do in Rust (and what to do instead)
by oconnor663 on Wednesday May 19, 2021 @09:44PM
(#27216463)
Yeah Crossbeam is awesome. And the pre-1.0 story about a similar interface that existed in std, until it was found to be unsound, is totally fascinating: https://github.com/rust-lang/rust/issues/24292. (Prior to that, std::mem::forget was marked unsafe!)
Another detail that's worth clarifying for folks reading along: The API in this example will automatically join all threads at the end of the crossbeam::scope. (That is indeed what makes it safe.) So if your goal is to fire off a background thread that will outlive the current function, you usually need to go back to std::thread::spawn and live with its 'static requirement.
Scoped threads are available in crossbeam, and they're pretty great, as sometimes it's convenient to borrow something from the stack.
Here's how I'd write that with scoped threads: