Ram
Ram

Reputation: 1193

share data in perl ithreads

Can I share data between threads. I have a simple code , I have am not able to share data across threads

use strict;
use LWP::UserAgent;
use threads;
use threads::shared;
my %threads_running :shared = ();
my %thread_data :shared = ();

$thread_data{1}=['a','b'];             #This line gives me an error

Upvotes: 1

Views: 65

Answers (2)

ikegami
ikegami

Reputation: 386551

$thread_data{1} = ['a','b'];  

is equivalent to

my @anon = ('a','b');
$thread_data{1} = \@anon;

You are trying to store a reference to an unshared variable into a shared variable. That's useless — how could the other threads access @anon? — so Perl gives an error.

You want

my @anon :shared = ('a','b');
$thread_data{1} = \@anon;

Or if you don't mind making a copy of the array,

$thread_data{1} = shared_clone(['a','b']);

Upvotes: 1

mpapec
mpapec

Reputation: 50667

Assigning reference to a shared variable requires to be shared one. You can try,

$thread_data{1} = threads::shared::shared_clone(['a','b']);

From perldoc

shared_clone takes a reference, and returns a shared version of its argument, performing a deep copy on any non-shared elements. Any shared elements in the argument are used as is (i.e., they are not cloned).

Upvotes: 1

Related Questions