如何在Perl中创建线程? [英] How to create threads in Perl?

查看:71
本文介绍了如何在Perl中创建线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的Perl脚本,其中有一个BIG循环,在此循环中,我调用了大约一百万次的函数my_fun().我想创建一个将要处理的线程池-同一时间最多5个线程将​​在循环中调用此方法.

I have got easy Perl script where I have got a BIG loop and inside this I invoke more or less million times function my_fun(). I would like to create pool of threads which will be dealing with it - max 5 threads in this same time will be invoking this method in loop.

使用最快的库对我来说真的很重要-看到示例真是太好了.

It is really important for me to use the fastest library - It will be really nice to see examples.

我的代码如下:

for (my $i = 0; $i < 1000000 ; $i++) {
        my_fun();
}

提前谢谢

推荐答案

看看 Parallel :: ForkManager .它使用的是fork而不是线程,但是它应该非常简单地完成您的工作.

Have a look at Parallel::ForkManager. It's using fork, not threads, but it should get your job done very simply.

示例从文档中删除,并稍作改动:

Example lifted from the docs and slightly altered:

use Parallel::ForkManager;

my $pm = Parallel::ForkManager->new(5); # number of parallel processes

for my $i (0 .. 999999) {
  # Forks and returns the pid for the child:
  my $pid = $pm->start and next;

  #... do some work with $data in the child process ...
  my_fun();

  $pm->finish; # Terminates the child process
}

$pm->wait_all_children;

这篇关于如何在Perl中创建线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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