两个使用 Perl threads 模块的例子。
例1 (>= Perl 5.8.8):
#!/usr/bin/perl
use strict;
use warnings;
use threads;
use threads::shared;
my $thread_num :shared = 0;
sub start_thread {
print "Thread ", threads->tid(), " started, current thread numbers $_[0]\n";
{
lock($thread_num);
$thread_num--;
cond_signal($thread_num);
}
}
for (1 .. 200) {
{
lock($thread_num);
cond_wait($thread_num) until $thread_num < 10;
my $t = threads->create(\&start_thread, $thread_num + 1);
$t->detach();
$thread_num++;
}
}
|
很奇怪的是,上面的例子创建的子线程的总数并不是 200 个。
在脚本的最后加上 sleep(2); 后,每次都能看到 200 个输出。看来是由于主线程提前结束,某些线程还没来得及打印信息就被结束掉了。例2 (>= Perl 5.10.0):
#!/usr/bin/perl
use strict;
use warnings;
use threads;
my $thread_num = 0;
sub start_thread {
print "Thread ", threads->tid(), " started, current thread number $_[0]\n";
}
for (1 .. 200) {
if ($thread_num >= 10) {
for my $t (threads->list(threads::joinable)) {
$t->join();
$thread_num--;
}
redo;
}
threads->create(\&start_thread, $thread_num + 1);
$thread_num++;
}
for my $t (threads->list()) {
$t->join();
}
|
例3 (>= Perl 5.8.8)
#!/usr/bin/perl
use strict;
use warnings;
use threads;
use Thread::Semaphore;
my $thread_num = Thread::Semaphore->new(10);
sub start_thread {
print "Thread ", threads->tid(), " started\n";
$thread_num->up();
}
for (1 .. 200) {
$thread_num->down();
while (1) {
if (my $t = threads->create(\&start_thread)) {
$t->detach();
last;
}
else { threads->yield(); }
}
}
|
这个也存在由于主线程提前结束,导致某些线程还没有打印信息就被结束的情况。
阅读(5975) | 评论(0) | 转发(0) |