http://www.perlmonks.org?node_id=1012593

PerlRider has asked for the wisdom of the Perl Monks concerning the following question:

Hi, I have some variables blessed with one Class. In one of the member functions of that Class, I created thread. I tried to access the Member variables directly from that Thread function as shown in the code below: I am unable to get the blessed variables data in the thread function. Can someone please let me know how to access them in thread function.

package PKG1; sub New { my($port, $ipadd) = @_; : : my $self = { ipaddress => $ipadd, port => $to_port, }; bless($self, $class); } sub Start { my ($self) = @_; my $tid = threads->new(\&threadFunc); $tid->join(); } sub threadFunc{ my($self) = @_; my($port, $ip); $ip = $self->{ipaddress}; $port = $self->{port}; } 1;

  • Comment on How to get Blessed variables of a Class in the Thread Function in Perl?
  • Download Code

Replies are listed 'Best First'.
Re: How to get Blessed variables of a Class in the Thread Function in Perl?
by NetWallah (Canon) on Jan 10, 2013 at 06:47 UTC
    That is because you neglected to pass $self as a parameter to the threaded call to threadFunc.

    Try:

    my $tid = threads->new(\&threadFunc , $self); # Syntax: $thr = threads +->create(FUNCTION, ARGS)

                 "By three methods we may learn wisdom: First, by reflection, which is noblest; Second, by imitation, which is easiest; and third by experience, which is the bitterest."           -Confucius

      Thanks all, I thought as normal member function and henc didnot give $self as an argument. Working fine after passing $self as argument.

Re: How to get Blessed variables of a Class in the Thread Function in Perl?
by vinoth.ree (Monsignor) on Jan 10, 2013 at 06:52 UTC
    Hi,

    Are you sure ? $self is defined? in threadFuncfunction?

    You need to pass the $self in

    threads->new(\&threadFunc);