Omniperl has asked for the wisdom of the Perl Monks concerning the following question:
Venerable monks, I'm here because I need your ancient knowledge referred to classes and threads and how they are interrelated.
I have one small package named HardThread.pm, and a tiny perl script that uses the package.
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"; return bless( \%{$inter}, $class ); } sub stop_thread { my $inter = shift; $inter->{THR}->kill('TERM'); $inter->{THR}->join(); } sub starter { my $inter = shift; $inter->{THR} = ref threads->create(sub{$thread->(\$inter->{INT1}) +}); return ( 1 ); } sub set_internal { my $inter = shift; if( @_ ) { my ( $given_key, $given_value ) = @_ if @_; $inter->{$given_key} = $given_value; return ( 1 ); } return ( 0 ); } sub printer { my $inter = shift; 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 script is:
#! /usr/bin/perl use strict; use warnings; use HardThread; my $var = HardThread->new(); $var->printer(); $var->starter(); while( <STDIN> ) { chomp $_; $var->set_internal("INT1", $_); } $var->stop_thread(); sleep 5;
And what is the target with all this?
Basically, I want to define a class named HardThread.pm that self-invokes a thread and offers public functions to manage it.
However, I want to make thread able to access to an internal variable stored in class in order to make visible for the thread any future changes made on this variable.
Code listed above does it very well, and running the script generates the desired output, but function stop_thread cannot execute functions $inter->{THR}->kill('TERM') and $inter->{THR}->join() and hence, the script cannot wait to thread termination. What is wrong?
Waiting for your wisdom, I send you best regards.
PD: Apologize if I don't write English very well. I'm not an English-speaker and I have some difficulties to write it. Thanks a lot! :)
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: About self-invoked threads into class
by BrowserUk (Patriarch) on Jun 01, 2012 at 14:10 UTC | |
by sundialsvc4 (Abbot) on Jun 01, 2012 at 19:06 UTC | |
by BrowserUk (Patriarch) on Jun 01, 2012 at 19:49 UTC | |
Re: About self-invoked threads into class
by Eliya (Vicar) on Jun 01, 2012 at 13:58 UTC |