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

Categories

0 votes
857 views
in Technique[技术] by (71.8m points)

multithreading - How to create threads in Perl?

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

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

1 Answer

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...