n久前写过的一个例子,供参考一下

use strict;
use threads;
use threads::shared; # 涉及到一些进程间变量的共享,用这个模块

my $process = 4;
my $child_num = 0;

while (1) {

    if ($child_num < $process){
        my $params = '..........';
        my $thr = threads->create(\&start_thread, $params);
        $child_num ++;
    }

    foreach my $t(threads->list(threads::joinable)){
        $t->join();
        $child_num --;
    }

    # all tasks done and no running child, then exit
    if ( "tasks done" && $child_num==0){
        exit;
    }

}

sub start_thread(){
    # do actually task here
    ............
}

2011/6/24 梁舒华 <[email protected]>

>
> 大家好!我想执行1000个线程,但每次同时执行的最大线程数目为4,这四条线程执行完后再执行另外四条线程,以下代码能实现这个要求。但这样不能充分利用cpu,能不能实现只要一条线程结束就马上生成新的线程,不要等四条都结束才建新的四条线程?
>
> #!/usr/bin/perl
> use strict;
> use warnings;
> use threads;
> use Thread::Semaphore;
>
> my $max_thread = 4;
> my $semaphore = Thread::Semaphore new( $max_thread );
>
> sub TestFun
> {
>     my $num = shift;
>         print "print $num in thread ".threads->self()->tid()."\n";
>         sleep( 1 );
>     }
>     # 线程技术,释放一个信号量
>     $semaphore->up( );
> }
>
> sub Wait2Quit
> {
>     print "Waiting to quit...\n";
>
>     my $num = 0;
>     while( $num < $max_thread )
>     {
>         # 尝试获取信号量,当能够获取到最大线程数个信号量时,表示所有线程都结束了
>         $semaphore->down( );
>         $num ++;
>         print "$num thread quit.\n";
>     }
>     print "All $max_thread thread quit.\n";
> }
>
> for( my $index = 1; $index <= 1000; $index ++)
> {
>     # 获取一个信号量,控制并行的线程数量
>     $semaphore->down( );
>     my $thread = threads->create( &TestFun, $index );
>
>     # 剥离线程,不关心返回值,系统自动回收资源
>     $thread->detach();
> }
>
> Wait2Quit( );
>
> --
> 您收到此邮件是因为您订阅了 Google 网上论坛的“PerlChina Mongers 讨论组”论坛。
> 要向此网上论坛发帖,请发送电子邮件至 [email protected]。
> 要取消订阅此网上论坛,请发送电子邮件至 [email protected]。
> 若有更多问题,请通过 http://groups.google.com/group/perlchina?hl=zh-CN 访问此网上论坛。
>

-- 
您收到此邮件是因为您订阅了 Google 网上论坛的“PerlChina Mongers 讨论组”论坛。
要向此网上论坛发帖,请发送电子邮件至 [email protected]。
要取消订阅此网上论坛,请发送电子邮件至 [email protected]。
若有更多问题,请通过 http://groups.google.com/group/perlchina?hl=zh-CN 访问此网上论坛。

回复