Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

My code looks like this:

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

Thank you in advance

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
884 views
Welcome To Ask or Share your Answers For Others

1 Answer

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...