请教,自己写的一个Perl多线程例子,请高人指点,是否存在问题!
#!/usr/bin/perl
use threads;
use threads::shared;
use Fcntl qw/:flock/;
my @threads;
my $item:shared = 0;
print time() . "\n";
#20个任务,10线程跑
for(my $i=0; $i<20; $i++) {
log2File ("---start one mission --$i--\n");
my $t = int(rand()*30);
if ($i == 12){
$t = 30;
}
#如果线程超过10个在运行,则等待
if ($item < 10){
$threads[$i]=threads->new(\&start_thread,$i,$t);
$threads[$i]->detach();
$item ++;
}
else{
while ($item >= 10){
log2File ("---超过10个线程在运行\n");
sleep 5;
}
}
}
while ($item > 0){
log2File ("---$item------------------------------\n");
sleep 5;
}
log2File ("---$item thread run.............\n");
log2File ("\n");
sub start_thread{
my ($id,$t)=@_;
sleep $t;
log2File ("---$id thread already sleep $t\n");
{
lock($item);
$item --;
log2File ("---$id thread item - 1 ...... $item\n");
}
}
sub log2File{
my ($event) = @_;
my $time = `date +"%Y-%m-%d %H:%M:%S"`;
my $date = `date +"%Y%m%d"`;
chomp($time);
chomp($date);
my $log_file = "./Log_" . $date . ".log";
open LOGFILE, ">>$log_file" or die "can't open $log_file!\n";
flock(LOGFILE, LOCK_EX) or die "Can't lock $log_file!\n";
print LOGFILE ("$time-----$event \n");
close LOGFILE;
}