Perl运行同步例程

问题描述:

我正在运行试图在perl中一次运行两个子例程。我能做的最好的方式是什么?例如:Perl运行同步例程

sub 1{ 
     print "im running"; 
    } 

sub 2{ 
     print "o hey im running too"; 
    } 

如何一次执行两个例程?

使用threads

use strict; 
use warnings; 
use threads; 

sub first { 

    my $counter = shift; 
    print "I'm running\n" while $counter--; 
    return; 
} 

sub second { 

    my $counter = shift; 
    print "And I'm running too!\n" while $counter--; 
    return; 
} 

my $firstThread = threads->create(\&first,15); # Prints "I'm running" 15 times 
my $secondThread = threads->create(\&second,15); # Prints "And I'm running too!" 
               # ... 15 times also 

$_->join() foreach ($firstThread, $secondThread); # Cleans up thread upon exit 

你应该注意的是印刷是如何不规则地交错的。不要试图在假设执行顺序良好的前提下进行任何计算。

Perl的线程可以互相通信使用:

  • 共享变量(use threads::shared;
  • 队列(use Thread::Queue;
  • 信号量(use Thread::Semaphore;

参见perlthrtut以获取更多信息和优异的教程。

+1

查看[这篇文章](http://stackoverflow.com/questions/2423353/can-we-run-two-simultaneous-non-nested-loops-in-perl)的相关问题。 – Zaid 2010-06-01 13:36:56

+0

感谢大家。欣赏它 – jtime08 2010-06-01 13:41:00

我居然没意识到,Perl可以做到这一点,但你需要的是支持多线程:

http://search.cpan.org/perldoc?threads

要么,叉两个过程,但是这将是一个有点难以隔离子例程的调用。

+0

这里有一个稍微容易追随的链接:http://perldoc.perl.org/perlthrtut.html#Thread-Basics – d11wtq 2010-06-01 13:16:26

+0

谢谢,我将看看它 – jtime08 2010-06-01 13:22:38

+3

d11wtq,请编辑您的答案:'线程'模块(大写字母T)甚至不再工作,已经被'threads'模块所取代。 – daxim 2010-06-01 15:07:12