Add JoinHandle::into_join_future(). by kpreid · Pull Request #131389 · rust-lang/rust (original) (raw)

I don't see a good solution except to document this as a caveat (and do the same for Thread::scope).

I’ve added a mention of this consideration to the documentation that this PR adds (i.e. not including Thread::scope). I wasn’t sure how best to insert it into the documentation without too many miscellaneous paragraphs on scattered topics; I decided to create a list of # Behavior details, but I’d like to know if there's something that would be more in line with existing std documentation idiom.

/// * Unlike [JoinHandle::join()], the thread may still exist when the future resolves. /// In particular, it may still be executing destructors for thread-local values.

I also note that this API design prevents one possible solution: run the JoinFuture, then after it completes, call blocking JoinHandle::join() on the assumption that it will complete quickly enough. But, that result can still be achieved by using an explicit channel instead of JoinFuture (the status quo), so this is fine as long as we see into_join_future() as a convenience feature rather than “should be able to be used for everything”.

Another approach, not reasonable in current std, would be to poll for thread completion on a timer, perhaps informed by a TLS destructor hook of its own, to avoid blocking — hm, actually, Thread::is_finished() has the exact same considerations, and it does have some documentation:

/// This might return true for a brief moment after the thread's main /// function has returned, but before the thread itself has stopped running. /// However, once this returns true, [join][Self::join] can be expected /// to return quickly, without blocking for any significant amount of time.

This doesn’t mention TLS specifically, and it makes the implicit claim that TLS destruction will complete quickly, which isn’t guaranteed. Should this be changed too? Regardless, it’s some additional precedent for not worrying too much about TLS destruction.