3

我需要 Perl 中的多线程方面的帮助。

基本逻辑是启动20个线程。我有一个数组@dataarray,我希望将 20 块数据传递给每个线程。比如说,@dataarray里面有 200 行数据,所以前 10 行将被发送到线程 1,接下来的 10 行应该被发送到线程 2,所以它们不会覆盖彼此的数据,最终在处理线程后应该更新返回结果到@outputarrayat与 source 相同的索引位置@datarray

例如:第 19 行(索引位置 18)从@dataarray被发送到线程 2,所以在处理它之后线程 2 应该更新$outputarray[18] = $processed_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();
    }
4

1 回答 1

6

我不认为我之前所说的必须使用threads::shared是正确的。我不得不去检查文档,我不确定。我永远不确定 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
于 2012-05-03T21:10:10.713 回答