Martin KS
Martin KS

Reputation: 531

How do you share arrays in threaded perl?

Inside the below sub (a simplified version of code causing an error), each thread should be adding to a master output list. While inside the sub, the array seems to be populating, but when I get back to the main calling portion, it’s empty again. What have I done wrong?

#!/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();
}

Upvotes: 3

Views: 893

Answers (1)

woolstar
woolstar

Reputation: 5083

According to the threads::shared documentation that @mpapec cited

By default, variables are private to each thread, and each newly created thread gets a private copy of each existing variable.

So the solution is the module:

use threads::shared ;

our @outputArray :shared ;

There are other forms you can use and a lot of limitations, so reading the entire document is recommended.

Upvotes: 4

Related Questions