llancet has asked for the wisdom of the Perl Monks concerning the following question:

use threads;
In the ActivePerl distribution, there is a method called "is_joinable" to judge whether a thread is completed and can be joined immediately.
However, I didn't find similiar method in the standard distribution. So, how can I know that a thread can be joined? Now, I use some ugly way to do this:
use threads; use threads::shared; my %thread_state:shared; # ignore the creation of threads # a loop that collects all threads while (1) { foreach (threads->list()) { if ($thread_state{$_->tid} eq 'finished') {$_->join;} } sleep 1; last if (&all_finished); } # the thread body looks like this sub thread_body{ # do something # when finished, mark itself { lock %thread_state; $thread_state{$threads->tid} = 'finished'; } }

Replies are listed 'Best First'.
Re: how to estimate thread state
by ikegami (Patriarch) on Sep 18, 2008 at 03:20 UTC
    is_joinable has been part of threads since v1.34 (July 2006). Why don't you upgrade your version of threads?
Re: how to estimate thread state
by BrowserUk (Patriarch) on Sep 18, 2008 at 08:57 UTC

    If all you are going to do when a thread is not yet joinable, is sleep and loop until it is, then you might as well just call join() and let it block until it is.

    With your loop as coded, it means that you may join early finishing threads a little quicker than you would without the loop, but as the loop doesn't terminate (or do anything else), until all the threads are joined, there is really very little benefit to that loop over just calling $_->join for threads->list;. The end result is exactly the same.

    The only times it makes sense to only call join if the thread has already finished, is if you are waiting to do something with the threads returned value, or want to start a new thread to replace the old one.


    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.