如何在Perl线程中共享数组?

3
在下面的子程序中(造成错误的代码的简化版本),每个线程都应该添加到主输出列表。虽然在子程序中,数组似乎正在填充,但当我回到主调用部分时,它又变为空了。我做错了什么吗?
#!/usr/bin/env perl

use threads;
use strict;

my $num_threads = 8;
my @threads = initThreads();
our @outputArray;

foreach(@threads){
    $_ = threads->create(\&do_search);
}

foreach(@threads){
    $_->join();
}

print "@outputArray";

sub initThreads{
    # An array to place our threads in
    my @initThreads;
    for(my $i = 1;$i<=$num_threads+1;$i++){
        push(@initThreads,$i);
    }
    return @initThreads;
}

sub do_search{
    my $id = threads->tid();
    push(@outputArray,$id);
    threads->exit();
}

3
http://perldoc.perl.org/threads/shared.html - mpapec
“our” 只是为程序包变量设置别名,而不会为其创建任何存储空间,对吗? - Bandrami
1个回答

4
根据@mpapec引用的threads::shared文档,默认情况下,变量对每个线程都是私有的,并且每个新创建的线程都会得到每个现有变量的一个私有副本。因此解决方案是使用该模块。
use threads::shared ;

our @outputArray :shared ;

还有其他可用的形式和许多限制,因此建议阅读整个文档。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接