如何并行运行子例程


for(i=0; i<5; i++)
{
  method1();
}
sub method1()
    {
           // here do something
    }

在这里,我称Method1子例程为循环。在这里,我希望(并行)此Method1子例程,而无需等待上一个呼叫的结果。怎么做 ?除线程外,还有其他方法吗?

线程:

use threads;
for (0..4) {
    async { f() };
}
$_->join() for threads->list;

流程:

use forks;
for (0..4) {
    async { f() };
}
$_->join() for forks->list;

coro线程:

use Coro;
my @threads;
for (0..4) {
    push @threads, async { f() };
}
$_->join() for @threads;

coro提供了一个合作的多任务系统,因此其他线程只有在当前的等待事件被阻止时才有机会执行。

最新更新