This example might show you a way. One thing you might be missing is that the thread must reach the end of it's code block, or return, before it can be joined. So I usually use a shared var 'die' to signal a thread to return immediately. That way, if you want to exit without all those warnings, you set the 'die' = 1 for each thread, then join them after they have returned.
In the following example, I join them as they finish, but you can easily hold them in an unjoined condition, until all threads are done. I don't know why you would want that, but it would be easy to do.
#!/usr/bin/perl
use warnings;
use strict;
use threads;
use threads::shared;
$| = 1;
my %threads;
foreach (1..10){
share $threads{$_}{'die'};
share $threads{$_}{'data'};
$threads{$_}{'die'} = 0;
$threads{$_}{'data'} = 0;
}
foreach (1..10) {
$threads{$_}{'thread'} = threads->new('StartTest');
}
my @threads = (1..10);
while(1){
foreach my $t (@threads){
if($threads{$t}{'data'} > 5){
$threads{$t}{'die'} = 1;
$threads{$t}{'thread'}->join;
@threads = grep { $_ != $t } @threads;
}
}
if(scalar @threads == 0){last}
}
print "\n", "All threads done\n";
##########################################################
sub StartTest {
my $self = threads->self;
print "Thread ", $self->tid, " started\n";
while(1){
if( $threads{$_}{'die'} == 1){return}
else{
print "From thread $self->",$threads{$_}{'data'}++,"\n";
sleep 1;
};
}
print "Thread ", $self->tid, " ending\n";
}
I'm not really a human, but I play one on earth.
flash japh
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.