I'd use a global shared hash rather than a "singleton object" which is just a fancy name for a global anyway, and gets you into a painful world of shared methods.
Simple and effective, I'd do it like this:
#! perl -slw
use strict;
use threads;
use threads::shared;
use Data::Dump qw[ pp ];
use Time::HiRes qw[ time sleep ];
my $sem :shared;
sub tprint {
lock $sem;
print @_;
}
my %config :shared;
sub loadConfig{
open my $fh, '<', 'junk.config' or die $!;
lock %config;
$config{ $_->[0] } = $_->[1] while @{ $_ = [ split ':', <$fh> ] };
tprint pp \%config;
tprint "Config refreshed at ", scalar time;
};
$SIG{'INT'} = \&loadConfig;
sub worker {
my $tid = threads->tid;
my $telltale = $config{ telltale };
while( sleep 0.01 ) {
if( $config{ telltale } ne $telltale ) {
tprint "[$tid] saw change at ", scalar time();
$telltale = $config{ telltale };
}
}
}
loadConfig();
my @workers = map threads->create( \&worker ), 1 .. 8;
while( threads->list > 1 ) {
$_->join for threads->list( threads::joinable );
sleep 0.1;
}
__END__
C:\test>921884.pl
{
# tied threads::shared::tie
bill => "leprechaun\n",
fred => 123
,
telltale => 1
,
}
Config refreshed at 1314106074.357
{
# tied threads::shared::tie
bill => "leprechaun\n",
fred => 123
,
telltale => 2
,
}
[3] saw change at 1314106084.6591
[4] saw change at 1314106084.66004
[5] saw change at 1314106084.66113
[6] saw change at 1314106084.66309
[1] saw change at 1314106084.66507
[7] saw change at 1314106084.66507
[2] saw change at 1314106084.66612
[8] saw change at 1314106084.66705
Config refreshed at 1314106084.66944
Terminating on signal SIGBREAK(21)
Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.
|