Context
The spawn
function returns a JoinGuard
object, which will automatically join the thread when dropped. This means that the next code snippet will spawn a new thread with expensive_fn
and will join it before doing the rest (so it will wait until expensive_fn
returns before executing cheap_fn
).
fn main() {
Thread::spawn(expensive_fn);
cheap_fn();
}
Discussion
I think this behavior can be surprising. Coming from C#, the natural thing to me seems that threads are detached unless you state otherwise. Rust seems to do the opposite. Why was this approach chosen instead of automatic detaching? Does any other language take this approach?