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


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).