Multithreading 在Perl中,如何使用多个线程来处理大型数组的一部分?
我需要Perl中多线程的帮助 基本逻辑是启动20个线程。我有一个数组Multithreading 在Perl中,如何使用多个线程来处理大型数组的一部分?,multithreading,perl,Multithreading,Perl,我需要Perl中多线程的帮助 基本逻辑是启动20个线程。我有一个数组@dataarray,我希望向每个线程传递20个数据块。比如说,@dataarray中有200行数据,所以前10行将被发送到线程1,下10行应该被发送到线程2,这样它们就不会覆盖彼此的数据,最终在处理后,线程应该将返回结果更新到@outputarray与源@datarray相同的索引位置 例如:@dataarray中的第19行(索引位置18)被发送到线程2,因此在处理它之后,线程2应该更新$outputarray[18]=$pr
@dataarray
,我希望向每个线程传递20个数据块。比如说,@dataarray
中有200行数据,所以前10行将被发送到线程1,下10行应该被发送到线程2,这样它们就不会覆盖彼此的数据,最终在处理后,线程应该将返回结果更新到@outputarray
与源@datarray
相同的索引位置
例如:@dataarray
中的第19行(索引位置18)被发送到线程2,因此在处理它之后,线程2应该更新$outputarray[18]=$processed\u string
只需要弄清楚如何将数组的各个位置发送到特定的线程
#!/usr/bin/perl
use strict;
use threads;
my $num_of_threads = 20;
my @threads = initThreads();
my @dataarray;
foreach(@threads)
{
$_ = threads->create(\&doOperation);
}
foreach(@threads)
{
$_->join();
}
sub initThreads
{
my @initThreads;
for(my $i = 1;$i<=$num_of_threads;$i++)
{
push(@initThreads,$i);
}
return @initThreads;
}
sub doOperation
{
# Get the thread id. Allows each thread to be identified.
my $id = threads->tid();
# Process something--- on array chunk
print "Thread $id done!\n";
# Exit the thread
threads->exit();
}
#/usr/bin/perl
严格使用;
使用线程;
我的$num_线程数=20;
my@threads=initThreads();
我的@dataarray;
foreach(@threads)
{
$\=threads->create(\&doOperation);
}
foreach(@threads)
{
$\->join();
}
子初始化线程
{
我的@init线程;
对于(my$i=1;$itid();
#在数组块上处理某物
打印“线程$id完成!\n”;
#退出线程
线程->退出();
}
我认为我之前所说的关于必须使用的内容是不正确的。我必须去查看文档,但我不确定。对于Perl线程,我从来都不确定
更新:事实证明,我的不完全理解再次暴露出来。至少,您需要threads::shared
才能将结果从每个线程中放入@output
#!/usr/bin/env perl
use strict; use warnings;
use threads;
use threads::shared;
use List::Util qw( sum );
use YAML;
use constant NUM_THREADS => 20;
my @output :shared;
my @data = ( ([1 .. 10]) x 200);
# note that you'll need different logic to handle left over
# chunks if @data is not evenly divisible by NUM_THREADS
my $chunk_size = @data / NUM_THREADS;
my @threads;
for my $chunk ( 1 .. NUM_THREADS ) {
my $start = ($chunk - 1) * $chunk_size;
push @threads, threads->create(
\&doOperation,
\@data,
$start,
($start + $chunk_size - 1),
\@output,
);
}
$_->join for @threads;
print Dump \@output;
sub doOperation{
my ($data, $start, $end, $output) = @_;
my $id = threads->tid;
print "Thread [$id] starting\n";
for my $i ($start .. $end) {
print "Thread [$id] processing row $i\n";
$output->[$i] = sum @{ $data->[$i] };
sleep 1 if 0.2 > rand;
}
print "Thread $id done!\n";
return;
}
输出:
- 55
- 55
- 55
…
- 55
- 55
- 55
- 55
- 55
- 55
- 55
…
- 55
- 55
- 55
- 55