Beefy Boxes and Bandwidth Generously Provided by pair Networks Russ
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: About self-invoked threads into class

by Eliya (Vicar)
on Jun 01, 2012 at 13:58 UTC ( #973763=note: print w/ replies, xml ) Need Help??


in reply to About self-invoked threads into class

but function stop_thread cannot execute functions $inter->{THR}->kill('TERM') and ...

Your immediate problem is that you're trying to call the kill method on the value

ref threads->create(...)

which is the string "threads", stored in $inter->{THR}, instead of the thread itself, i.e. what threads->create(...) returns.  However, when trying to fix the problem by getting rid of the "ref"

$inter->{THR} = threads->create(sub{$thread->(\$inter->{INT1})});

you'd get an "Invalid value for shared scalar" error...

So, you probably want to take the thread variable out of the shared data structure, e.g. modify your code like this

package HardThread; use strict; use warnings; use threads; use threads::shared; use vars qw( $internal ); ## Variable declaration for internal functions my ( $thread ); sub new { my $class = shift; my $inter : shared = shared_clone({}); $inter->{INT1} = "internal 1"; $inter->{INT2} = "internal 2"; $inter->{INT3} = "internal 5"; my $self = {}; $self->{inter} = $inter; return bless $self, $class; } sub stop_thread { my $self = shift; $self->{THR}->kill('TERM'); $self->{THR}->join(); } sub starter { my $self = shift; my $inter = $self->{inter}; $self->{THR} = threads->create(sub{$thread->(\$inter->{INT1})}); return ( 1 ); } sub set_internal { my $self = shift; my $inter = $self->{inter}; if( @_ ) { my ( $given_key, $given_value ) = @_ if @_; $inter->{$given_key} = $given_value; return ( 1 ); } return ( 0 ); } sub printer { my $self = shift; my $inter = $self->{inter}; foreach my $key ( keys %{$inter} ) { print $key, " - ", $inter->{$key}, "\n"; } } $thread = sub { local *internal = $_[0]; my $control = 1; $SIG{'TERM'} = sub { $control = 0; }; while( $control == 1 ) { print "Thread shows internal value: ", $internal, "\n"; sleep 2; } return ( 1 ); }; 1;

The idea is to have a "wrapper" hash/object, which stores

$self->{inter} # access to shared data $self->{THR} # access to thread

With these modifications, the code works fine for me (if I'm understanding your intentions correctly).


Comment on Re: About self-invoked threads into class
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://973763]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (8)
As of 2014-04-20 11:48 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    April first is:







    Results (485 votes), past polls