Perl 的多线程

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]

    原文作者:vicyang
    原文地址: https://www.jianshu.com/p/8523e5253352
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞