给一个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";
没有评论:
发表评论