perl-多线程
perl-多线程1.创建多线程
Thread->new(\&start_thread,$mho);
&start_thread是子函数,用来运行线程所执行的内容。
$mho传递给子函数的参数。
2.实例
#!/perl
use strict;
use Thread;
#use threads::shared;
my @threads;
my $mhofile = @ARGV;
open(MHO,"$mhofile");
my @mholist=<MHO>;
#print "@mholist\n";
foreach my $mho (@mholist) {
next unless defined $mho;
print "start one thread :\n";
$threads=Thread->new(\&start_thread,$mho);
$tempcount++;
}
foreach my $thread (@threads) {
$thread->join();
}
sub start_thread{
my ($infomho)=@_;
print "in thread $infomho";
sleep 20;
}
这里建立了多个线程:$threads=Thread->new(\&start_thread,$mho);
启动了多干个线程后,我们这里一定要使用变量保存thread的id。因为,创建一个thread以后要用join取得该thread的返回值,然后系统才会对thread进行清理,否则所有thread的信息都会保留下来,当然越积越多了。
所以,在最后我们要等待这些线程的完全退出:
foreach my $thread (@threads) {
$thread->join();
}
页:
[1]