-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Description
Currently, the only way to spawn a thread is with 'static lifetime bounds on the closure and its return type. This makes sense for regular threads with an indeterminate lifetime. However, the std::thread module could also expose an explicitly unsafe way for spawning threads, with function signatures like the following:
//in std::thread
impl Builder {
pub unsafe fn spawn_unchecked<F, T>(self, f: F) -> io::Result<JoinHandle<T>>
where
F: FnOnce() -> T,
F: Send + 'a,
T: Send + 'a {...}
}and (for the free-standing version)
//in std::thread
pub unsafe fn spawn_unchecked<F, T>(self, f: F) -> io::Result<JoinHandle<T>>
where
F: FnOnce() -> T,
F: Send + 'a,
T: Send + 'a {...}Since the implementation of of Builder::spawn relies on unsafe code itself and the std::sys::thread types/functions don't require 'static lifetime bounds (haven't checked for all), this should be comparatively easy to implement by refactoring the spawn implementation into spawn_unchecked and calling that function with 'static lifetime bounds for the safe API.
The benefits would mainly be:
- users could use the unsafe API to spawn "scoped" threads without resorting to external crates if they so desire (adding the responsibility to ensure manual joining of course)
- safe and general implementations for actual scope threads could be simplified and made (slightly) more efficient
Currently, scoped thread implementations have to use a lot of tricks with their return types and lifetime transmuting to get to work. Results have to be separately allocated and internally set instead of using the std::thread::JoinHandle type, which would be much more fitting if not for the lifetime bounds on the spawn functions.
To summarize, scoped threads could be implemented more safely and with fewer allocations.