threads->tid()
threads->tid();
threads->self();
的正確用法:在線程函數內使用,或者在線程對象上使用
use threads;
my $th = threads->create(\&func, $i+1 );
$th->join();
printf "outside: %d\n", $th->tid();
sub func
{
my ($id) = @_;
printf "inside: %d\n", threads->tid();
}
tid 值是以1為起點的線程編號
join
join 的特點在于,必須等待所有線程挨個跑完,而不是同時進行
my $n = 5;
for my $i ( 0 .. $n-1 )
{
$th[$i] = threads->create(\&func, $i+1 );
$th[$i]->join();
}
sub func
{
my ($id) = @_;
my $t = $id/10.0;
sleep $t;
print "in thread $id, sleep ${t}s\n";
}
輸出以及耗時
in thread 1, sleep 0.1s
in thread 2, sleep 0.2s
in thread 3, sleep 0.3s
in thread 4, sleep 0.4s
in thread 5, sleep 0.5s
[Finished in 2.2s]