Takkun
Takkun

Reputation: 6361

How can I pass shared data to threads in Perl?

use threads;
use threads::shared;

sub test {
    my $s :shared = 22;
    my $thread = threads->new(\&thrsub);

    $thread->join();
    print $s;

}

sub thrsub {
    $s = 33;
}

test;

Why isn't the data being shared in the thread?

Upvotes: 1

Views: 980

Answers (2)

ikegami
ikegami

Reputation: 385506

It shares the variable, but you're accessing a different variable than the one you shared. (use strict; would have told you there were different variables in this case. Always use use strict; use warnings;) The fix is to use a single variable.

my $s :shared = 22;

sub test {
    my $thread = threads->new(\&thrsub);
    $thread->join();
    print $s;
}

sub thrsub {
    $s = 33;
}

test;

Upvotes: 5

Sinan Ünür
Sinan Ünür

Reputation: 118118

You misunderstood what threads::shared does. It does not give access to variables across lexical scopes. If you want thrsub to affect $s, you'll have to pass a reference to it when you create the thread.

use strict; use warnings;
use threads;
use threads::shared;

sub test {
    my $s = 22;
    my $s_ref = share $s;
    my $thread = threads->new(\&thrsub, $s_ref);

    $thread->join();
    print $s;

}

sub thrsub {
    my $s_ref = shift;
    $$s_ref = 33;
    return;
}

test;

Upvotes: 3

Related Questions