2009/12/21

Perl Threads

不得不说,perl 在M$ windows 下面实现的模拟fork真的是不堪一用,有很多限制,比如说: 不能fork 超过64次。也不能怪Perl,windows 对进程的处理就跟 Unix 大不相同!不过好在对于Thread的支持 Windows倒是没什么大问题。

给一个Windows下Perl多线程编程的小例子,自己留着慢慢用:) 里面用到:线程同步,变量共享。(需要Perl 5.8或者以上版本来支持 threads模块; say 这个好像是 Perl 5.10的feature, 其实就就print自动帮你加一个回车换行!)

use strict;
use warnings;

use feature qw(switch say);

use threads;
use threads::shared;
use Thread::Semaphore;

my $n = 9;

# shared variant across threads
my $arg :shared;

sub thread_proc
{
    my $sem = shift;

    for (1..$n) {
        # TODO: prepare works.
        sleep(1); # dummy 
        
        # wait until main thread wait me up!
        $sem->down;

        # TODO: Do my business~~~
        say "thread: $arg"; # dummy task
        sleep(1);   # dummy
    }

    say "thread_proc is over";
}

my $sem = new Thread::Semaphore();
my $thr = threads->create('thread_proc', $sem);
$sem->down; # Lock the semaphore

# Main thread
for(1..9)
{           
    # TODO: prepare works
    $arg = "$_ String " . ($_ * 1273);
    say "main: $arg";

    # Wait up the thread
    $sem->up;

    # TODO: Do some other works.
    sleep(3); # dummy task;
}

# wait for the thread to die
$thr->join();

print "end \n";

发表评论