bluesea007
bluesea007

Reputation: 211

How can I share object between threads in Perl?

I have searched for related topic, but still can't solve the problem...

use threads;
my $person = new Person( 'Name' => "yy");

my $udp_thread = threads->new(\&udp_func);

while(1)
{
    $person->working();
}

sub udp_func 
{
    #Can't call method "setName" on an undefined value:
    $person->setName();             
}

How can I visit the object $person in the new thread ? Thanks very much!!

Upvotes: 3

Views: 3909

Answers (1)

jonjbar
jonjbar

Reputation: 4066

Did you have a look at the threads::shared Perl extension ?

threads::shared - Perl extension for sharing data structures between threads. By default, variables are private to each thread, and each newly created thread gets a private copy of each existing variable. This module allows you to share variables across different threads (and pseudo-forks on Win32). It is used together with the threads module. This module supports the sharing of the following data types only: scalars and scalar refs, arrays and array refs, and hashes and hash refs.

Upvotes: 4

Related Questions