请介绍一个 Perl 或 Ruby 的多处理库 [英] Please introduce a multi-processing library in Perl or Ruby
问题描述
在 python 中,我们可以使用多处理模块.如果 Perl 和 Ruby 有类似的库,你会教吗?如果您能提供一个简短的示例,我将不胜感激.
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.
推荐答案
有了 Perl,您就有了选择.一种选择是使用如下流程.我需要查找如何使用线程编写类似的程序,但是 http://perldoc.perl.org/perlthrtut.html 应该给你一个想法.
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__
有趣的是:
TimeThis : Command Line : t.pl
TimeThis : Elapsed Time : 00:00:01.281
这篇关于请介绍一个 Perl 或 Ruby 的多处理库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!