Chinaunix首页 | 论坛 | 博客
  • 博客访问: 311167
  • 博文数量: 48
  • 博客积分: 4510
  • 博客等级: 中校
  • 技术积分: 556
  • 用 户 组: 普通用户
  • 注册时间: 2008-04-05 18:19
文章分类

全部博文(48)

文章存档

2012年(1)

2011年(9)

2010年(1)

2009年(12)

2008年(25)

分类:

2009-07-01 21:15:48

两个使用 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(); }
    }
}


这个也存在由于主线程提前结束,导致某些线程还没有打印信息就被结束的情况。
阅读(5915) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~