Perl 运行同步例程 [英] Perl running simultaneous routines

查看:45
本文介绍了Perl 运行同步例程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 perl 中一次运行两个子例程.我能做到的最好方法是什么?例如:

I am running trying to run two sub routines at once in perl. What is the best way I can about doing that? For example:

sub 1{
        print "im running";
     }

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

如何同时执行两个例程?

How can I execute both routines at once?

推荐答案

使用 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

你应该注意的是印刷是如何不规则交错的.不要试图根据执行顺序良好的错误前提进行任何计算.

What you should pay attention to is how the printing is interleaved irregularly. Don't try to base any calculations on the false premise that the execution order is well-behaved.

Perl 线程可以使用以下方式相互通信:

Perl threads can intercommunicate using:

  • 共享变量(use threads::shared;)
  • 队列(使用线程::队列;)
  • 信号量(使用线程::信号量;)

请参阅 perlthrtut 了解更多信息和优秀教程.

See perlthrtut for more information and an excellent tutorial.

这篇关于Perl 运行同步例程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆