Please introduce a multi-processing library in Perl or Ruby

后端 未结 5 739
囚心锁ツ
囚心锁ツ 2021-02-04 20:42

In python we can use multiprocessing modules. If there is a similar library in Perl and Ruby, would you teach it? I would appreciate it if you can include a brief sample.

5条回答
  •  孤街浪徒
    2021-02-04 21:11

    With Perl, you have options. One option is to use processes as below. I need to look up how to write the analogous program using threads but http://perldoc.perl.org/perlthrtut.html should give you an idea.

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    
    use Parallel::ForkManager;
    
    my @data = (0 .. 19);
    
    my $pm = Parallel::ForkManager->new(4);
    
    for my $n ( @data ) {
        my $pid = $pm->start and next;
        warn sprintf "%d^3 = %d\n", $n, slow_cube($n);
        $pm->finish;
    }
    
    sub slow_cube {
        my ($n) = @_;
    
        sleep 1;
        return $n * $n * $n;
    }
    
    __END__
    

    The following version using threads does not use a limit on the number of threads created (because I do not know how):

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    
    use threads;
    
    my @data = (0 .. 19);
    my @threads = map { 
        threads->new( {context => 'list' }, \&slow_cube, $_ )
    } @data;
    
    for my $thr ( @threads ) {
        my ( $n, $ncubed ) = $thr->join;
        print "$n^3 = $ncubed\n";
    }
    
    sub slow_cube {
        my ($n) = @_;
    
        sleep 1;
        return $n, $n * $n * $n;
    }
    
    __END__
    

    Interestingly:

    TimeThis :  Command Line :  t.pl
    TimeThis :  Elapsed Time :  00:00:01.281
    

提交回复
热议问题