#use threads::shared;
my @mholist=<MHO>;
next unless defined $mho;
print "start one thread";
$threads[$tempcount]=Thread->new(\&start_thread,$mho);
}
foreach my $thread (@threads) {
$thread->join();
}
my ($infomho)=@_;
print "in thread $infomho";
foreach my $thread (@threads) {
$thread->join();
}
否则,threads库会在最后打印如下信息:
A thread exited while 2 threads were running .
Perl中的多线程的实现一般有两种办法,而老版本的办法实际上是一种多进程的办法。
一 Thread->New
该办法是传统的老办法,它与folk很类似,新建一个进程时,会把当前内存空间的所有变量都复制一份传到新的进程里面。已实现共享数据。而随着技术的发展,本文不针对该方法做深入研究。
二 IThread
这种方法是通过新建一个新的 perl interpreter 。默认情况下,所有的数据和变量是不被线程共享的。如果想共享一个变量,需通过 threads::shared 来实现。在使用此方法的时候,需要注意以下三点:
- 变量默认是不在线程中共享的。
- 通过 "use threads" 引用命名空间,不能通过 , do, 或者 require。
- 如果有变量需要共享,必须引用 "threads::shared"。 并在定义变量的时候如下:
my $var1 : shared = "value";
以下是一个简单的使用perl 多线程的例子。

# !/ usr / local / bin / perl
use threads;
@domain = ( " tom.com " , " chinadns.com " , " 163.com " , " aol.com " );
for ($i = 0 ;$i < 4 ;$i ++ )
{
print $i. ' . ' .$domain[$i]. ' ' ;
}
print " \n " ;
my $thr0 = threads -> new (\ & checkwhois, ' 0 ' , $domain[ 0 ]);
my $thr1 = threads -> new (\ & checkwhois, ' 1 ' , $domain[ 1 ]);
my $thr2 = threads -> new (\ & checkwhois, ' 2 ' , $domain[ 2 ]);
my $thr3 = threads -> new (\ & checkwhois, ' 3 ' , $domain[ 3 ]);
sub checkwhois()
{
my ($l,$r) = @_;
my $i = 0 ;
while ($i < 1000000 )
{
$i * $i;
$i ++ ;
}
print " done --$l\t\n " ;
print $l.$r. " query successful! \n " ;
}
$thr0 -> join;
$thr1 -> join;
$thr2 -> join;
$thr3 -> join;
这个简单的perl主要是新建了4个子线程去做不同的事情,然后调用join方法等待他们执行完成并让线程自动回收
但有时,还是需要结合folk 做一些复杂的工作,下面是关于这个的例外一个demo。看原文连接
例子三:
perl多线程编程给我的总体感觉有点像 Linux C POSIX 多线程编程。 perl 多线程编程使用起来非常方便,但要深入掌握还是要下点功夫的。这里有一个简单的例子:
#!/bin/perl
use strict;
use threads;
use Cwd;
use POSIX qw(strftime);
################################################################################
# 函数名: count
# 函数描述: 数数
# 输入: name 随意输入一个名字
# 输出: 无
# 调用:
# 被调用:
# 返回:
################################################################################
sub count
{
my ($name) = @_;
my $current_time = strftime "%Y-%m-%d %H:%M:%S", localtime;
for ($i = 0; $i <= 10000; $i++)
{
print "$current_time $name $i";
}
}
创建第一批线程
my $thread_1_01 = threads->create('count', Thread_1);
my $thread_1_02 = threads->create('count', Thread_2);
my $thread_1_03 = threads->create('count', Thread_3);
my $thread_1_04 = threads->create('count', Thread_4);
# 等待第一批线程结束完成
$thread_1_01->join();
$thread_1_02->join();
$thread_1_03->join();
$thread_1_04->join();
# 创建第二批线程
my $thread_2_01 = threads->create('count', Thread_5);
my $thread_2_02 = threads->create('count', Thread_6);
my $thread_2_03 = threads->create('count', Thread_7);
# 等待第二批线程结束完成
$thread_2_01->join();
$thread_2_02->join();
$thread_2_03->join();