简体   繁体   English

与Coro并行运行perl子例程

[英]Running perl subroutine in parallel with Coro

I have a subroutine which I would like to execute in parallel with Coro : 我有一个子例程,我想与Coro并行执行:

use strict;
use warnings;
use Coro;

sub mysub {
    my ($in) = @_;
    print "$in \n";
    foreach my $i (0..100000000){
    $i=$i+1;
    }
    return 1;
}

from the Coro intro I read how I can create threads: Coro简介中,我了解了如何创建线程:

for ( 
    ( async{ mysub "A"  }   ),
    ( async{ mysub "B"  }   ),
    ( async{ mysub "C"  }   ),
    ( async{ mysub "X"  }   ),
    ( async{ mysub "Y"  }   )
    ) {
    $_->join;
}

However, threads are created but how can I run them all in parallel? 但是,创建了线程,但是如何并行运行它们呢? The example states that Coro::Socket (or better AnyEvent::Socket ) makes parallel execution possible but how can I make this work in my simple example? 该示例说明了Coro :: Socket (或更好的AnyEvent::Socket )使并行执行成为可能,但是如何在我的简单示例中实现此目的?

Also (but this is a second question), why does in the above for-loop the arguments to mysub get passed but not in the example below? 另外(但这是第二个问题),为什么在上面的for循环中传递mysub的参数,但在下面的示例中没有传递?

my @letters = ("A", "B", "C", "X", "Y");
my @in = map { (async {mysub $_ }) } @letters;
for ( @in ) {$_->join};

Coro is a co-operative multitasking system. Coro是一个协作式多任务处理系统。 A thread will only cede the CPU to another when the program explicitly does so, or when it's blocked waiting for an event in a Coro-aware call. 只有在程序显式地将线程割让给另一个线程时,或者在等待Coro-aware调用中的某个事件而将其阻塞时,线程才会将其让给另一个CPU。

For example, the following will wait for HTTP responses on parallel: 例如,以下将并行等待HTTP响应:

use Coro                          qw( async );
use LWP::Protocol::AnyEvent::http qw( );
use LWP::UserAgent                qw( );

...

for my $url (@urls) {
    async { process( $ua->get($url) ) };
}

...

Coro is powerless to split arithmetic among CPUs as your example attempts to do since it doesn't create any OS threads. 由于Coro不会创建任何OS线程,因此无法像您的示例一样在CPU之间分配算法。

Coro does not run the coroutines in parallel, only asynchronous. Coro不并行运行协程,而仅异步运行。 See documentation: 请参阅文档:

...They are similar to kernel threads but don't (in general) run in parallel at the same time even on SMP machine.. ...它们类似于内核线程,但是(通常)即使在SMP机器上也不能同时并行运行。

Instead it will switch between "threads" at usually blocking points, like read, write etc, but there will be only one "thread" running at a specific time. 相反,它将在通常的阻塞点(如读取,写入等)之间在“线程”之间切换,但是在特定时间仅运行一个“线程”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM