0

I am writing a perl script to get the exit status of each thread from the parent process. if i use join() i am not able to get the thread proper exit status.

how to capture the exit status of each thread from parent process ?

here is code

foreach (@threads) {
    $_->join();
}

sub sub1 {
    print "I am thread1\n";
    exit(20);
}

sub sub2 {
    print "I am thread2\n";
}

sub sub3 {
    print "I am thread3\n";
}

sub sub4 {
    print "I am thread4\n";
}

sub sub5 { 
    my $i=10/0;
    print "$i\n";
    print "I am thread5\n";
}
Tripp Kinetics
  • 5,178
  • 2
  • 23
  • 37
shreeshail
  • 59
  • 6

4 Answers4

1

First you'll have to use threads->exit as exit exits the whole process. Also, you'll have to die instead, inside thread to signal exception to the main thread.

Main thread can check for exception before or after joining the thread using

if (defined $thread->error) ..

From perldoc

$thr->error()

Threads are executed in an eval context. This method will return undef if the thread terminates normally. Otherwise, it returns the value of $@ associated with the thread's execution status in its eval context.

Community
  • 1
  • 1
mpapec
  • 50,217
  • 8
  • 67
  • 127
0

Don't use exit to abort a subroutine if there's any chance that someone might want to trap whatever error happened. Use die instead, which can be trapped by an eval. The exit() function does not always exit immediately. It calls any defined END routines first, but these END routines may not themselves abort the exit.

Also see: http://perldoc.perl.org/threads.html#EXITING-A-THREAD

Chankey Pathak
  • 21,187
  • 12
  • 85
  • 133
  • ok. if exception occurs ( divide by zero in sub5) or if user press CTRL+C during execution of threads, then how to capture it in main program – shreeshail Jun 13 '14 at 07:40
0

Might be better off just returning the value you want to return. join returns that value.

my $thread = async { return "foo" };
say $thread->join();  # foo
ikegami
  • 367,544
  • 15
  • 269
  • 518
0

You can always have the thread return a status code, rather than calling exit(). join() allows capturing a returned result from the sub, provided you started your thread in a suitable context.

my $thr = threads -> create ( \&sub1 );
foreach my $thr ( threads -> list() )
{
    my $result = $thr -> join();
    print "Got result of $result from thread ", $thr -> tid(),"\n";
}

sub1 {
  print "I am thread1";
  return 20;
}
Sobrique
  • 52,974
  • 7
  • 60
  • 101