Doug
Doug

Reputation: 35136

How can you wait for detached threads or control how threads are spawned?

When spawn is called, a JoinHandle is returned, but if that handle is discarded (or not available, somewhere inside a crate) the thread is "detached".

Is there any way to find all threads currently running and recover a JoinHandle for them?

...my feeling is that, in general, the answer is no.

In that case, is there any way to override either how Thread is invoked, or how JoinHandle is dropped, globally?

...but looking through the source, I can't see any way this might be possible.

As motivation, this very long discussion proposes using scopes to mandate the termination of child threads; effectively executing a join on every child thread when the scope ends. However, it requires that child threads be spawned via a custom method to work; it would very interesting to be able to do something similar in Rust where any thread spawned was intercepted and parented to the active ambient scope on the threadlocal.

I'll accept any answer that either:

Upvotes: 3

Views: 832

Answers (1)

Shepmaster
Shepmaster

Reputation: 430514

Is there any way to find all threads currently running and recover a JoinHandle for them?

No, this would likely impose restrictions/overhead on everyone who wanted to use threads, which is antithetical for a systems programming language.

You could write your own solution for this by using something like Arc/Weak and a global singleton. Then you have your own registry of threads.

is there any way to override either how Thread is invoked, or how JoinHandle is dropped, globally?

No, there is no ability to do this with the Rust libraries as they exist now. In fact "overriding" something on that scale is fairly antithetical to the concepts of a statically-compiled language. Imagine if any library you use could decide to "override" how addition worked or what println did. Some languages do allow this dynamicism, but it comes at a cost. Rust is not the right language for that.

In fact, the right solution for this is nothing new: just use dependency injection. "Starting a thread" is a non-trivial collaborator and likely doesn't belong to the purview of most libraries as it's an application-wide resource.

can be recovered before it is dropped

In Rust, values are dropped at the end of the scope where they are last used. This would require running arbitrary code at the prologue of arbitrary functions anywhere in the program. Such a feature is highly unlikely to ever be implemented.


There's some discussion about creating a method that will return a handle that joins a thread when it is dropped, which might do what you want, but people still have to call it .

Upvotes: 2

Related Questions