Join threads on drop

I've just realize that we could add the following function to std

impl<T> JoinHandle {

    pub fn join_on_drop(self) -> Self;

}

This function just sets an internal flag on the handle object, which is then checked in the drop implementation to .join().unwrap() the thread (propagating a panic).

This seems like a quick win for structured concurrency, much lighter weight than using a custom library for this pattern.

Was this suggested in the past? The idea seems obvious in retrospect, but I don't recall any discussions

4 Likes

(Small technical suggestion: this could be made zero-cost by returning a transparent wrapper type instead of setting a flag in memory)

5 Likes

I believe that this is how the old, unsound, scoped-thread API worked. In any case, std::thread::scope does something very similar, in a more-robust-but-less-flexible manner.

3 Likes

panic-in-drop is discouraged, there even is RFC PR 3288 that proposes to turn those into aborts by default.

4 Likes

I'm a big fan of implicit panic propagation - that's how we handle panics with normal function calls. But double panic abort in this case would significantly hurt DX. To keep the metaphor that scope.spawn(func) is just a function call but in parallel, I believe the right strategy is to propagate panic from spawned threads by default but skip it during panic unwinding. But I understand that it can be considered too smart and surprising for stdlib impl.

1 Like