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

Hey all,

I haven't played around to much with Threads in perl so far, so I'm trying to determine a way to catch errors that a particular thread throws without hanging the main script.

Note - I am using perl 5.8.8 and using the "threads" package, with "threads::shared" for thread communication.

If I spawn a thread like so:
threads->new ( \&myThreadFunction, $param );

and that thread dies during execution, is there a clean way to catch the error and allow the program to continue? I am assuming the other threads that might have been spawned will continue until completion, but it seems as if the parent throws a "thread failed to start" error and hangs in the while loop waiting for the "completed" counters to finish up.

Thanks for the help.

Replies are listed 'Best First'.
Re: catching threads that die
by BrowserUk (Patriarch) on Dec 05, 2008 at 02:06 UTC
    is there a clean way to catch the error and allow the program to continue? ... but it seems as if the parent throws a "thread failed to start" error and hangs

    Cannot reproduce. I get the error message, but not the hang?

    #! perl -slw use strict; use threads; sub condemned { my $tid = threads->tid; my $deathtime = time() + shift; while( sleep 1 ) { printf "$tid : %s\n", scalar localtime; die "T'is a far, far better thing I do now...." if time() > $deathtime; } } sub survivor { my $tid = threads->tid; for ( 1.. 5 ){ sleep 1; printf "$tid : %s\n", scalar localtime; } } my @threads = threads->create( \&condemned, 3 ); push @threads, map threads->create( \&survivor ), 1 .. 3; $_->join for @threads; __END__ c:\test>junk 10 1 : Fri Dec 5 02:04:19 2008 2 : Fri Dec 5 02:04:19 2008 3 : Fri Dec 5 02:04:19 2008 4 : Fri Dec 5 02:04:19 2008 1 : Fri Dec 5 02:04:20 2008 3 : Fri Dec 5 02:04:20 2008 2 : Fri Dec 5 02:04:20 2008 4 : Fri Dec 5 02:04:20 2008 1 : Fri Dec 5 02:04:21 2008 2 : Fri Dec 5 02:04:21 2008 3 : Fri Dec 5 02:04:21 2008 4 : Fri Dec 5 02:04:21 2008 1 : Fri Dec 5 02:04:22 2008 Thread 1 terminated abnormally: T'is a far, far better thing I do now. +... at c:\test\junk.pl line 10. 4 : Fri Dec 5 02:04:22 2008 3 : Fri Dec 5 02:04:22 2008 2 : Fri Dec 5 02:04:22 2008 4 : Fri Dec 5 02:04:23 2008 2 : Fri Dec 5 02:04:23 2008 3 : Fri Dec 5 02:04:23 2008
    hangs in the while loop waiting for the "completed" counters to finish up.

    If you posted the code, we might stand a chance of understanding what that means?


    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.