Re: Perl threads



On Mon, 30 Jul 2007 08:55:55 -0000, ivakras1@xxxxxxxxx wrote:

Hi all!
I have a perl threads question. Of cuz i have read perl threads
tutorial and think its clear to me. But some questions...
Q1: Is threads->create method only creates thread, but not runs theads
until im join it (or detach)?

The thread starts running as soon as you create it.

There are some simple rules.
1. A thread, whether joinable or detached, MUST return, or reach the end
of it's code block, for it to terminate. That means you may need some
logic with shared variables, to signal a thread to return, if you want
to avoid the "a thread exited while x running" warning. The warning
is harmless, unless the threads were doing something that needed a clean
finish. Joining by itself, WILL NOT terminate a thread, unless it has
returned first.

2. Use alot of shared variables to track and control your threads.

3. You have 2 ways to get return values from a thread. One is through
shared variables, and the other is through the return array.


#!/usr/bin/perl
use threads;

# join() does three things: it waits for a thread to exit,
# cleans up after it, and returns any data the thread may
# have produced.

$thr1 = threads->new(\&sub1);
$ReturnData1 = $thr1->join;
print "Thread1 returned @$ReturnData1\n";

$thr2 = threads->new(\&sub2);
$ReturnData2 = $thr2->join;
print "Thread2 returned @$ReturnData2\n";

$thr3 = threads->new(\&sub3);
$ReturnData3 = $thr3->join;
print "Thread3 returned @$ReturnData3\n";


sub sub1 {
print "In thread1.....\n";
sleep 10;
@values = ('1a','1b', '1c');
return \@values;
}

sub sub2 {
print "In thread2.....\n";
sleep 10;
@values = ('2a','2b', '2c');
return \@values;
}

sub sub3 {
print "In thread3.....\n";
sleep 10;
@values = ('3a','3b', '3c');
return \@values;
}
__END__

############################################
Some pseudo-code for terminating early:

#in main thread
my $die:shared = 0;
for( 1 .. 10 ){$thr = threads->new(\&thread_code);}
....
....
if( $foobar ==42 ){ clean_exit() }

sub clean_exit{
$die =1;
$_->join for threads->list();

}


#in thread
sub thread_code{
for (1..10){
if( $die == 1){return}
print "$_\n";
sleep 1;
}

print "I'm at the end of my code block, and ready to be joined\n";

}


zentara


--
I'm not really a human, but I play one on earth.
http://zentara.net/japh.html
.



Relevant Pages