How to create threads in Perl?

前端 未结 3 1349
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-11 12:10

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 th

3条回答
  •  执笔经年
    2020-12-11 13:07

    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;
    

提交回复
热议问题