4 ms·
You mention this, but I want to clarify that you only need reference counting due to using only std, not due to limitations in the language. Scoped threads are
by tene 5y ago
You mention this, but I want to clarify that you only need reference counting due to using only std, not due to limitations in the language.
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:
let my_string = Mutex::new(String::new());
crossbeam::scope(|s| {
for _ in 0..10 {
s.spawn(|_| {
let mut guard = my_string.lock().unwrap();
guard.push_str("some characters");
});
}
}).unwrap();
- oconnor663 5y agoYeah 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 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.