Subject: | variables defined after threads created not shared |
As demonstrated by the attached test case, shared variables that are
defined after threads have already been cloned are not correctly shared.
Instead, each of the existing threads gets its own private copy of the
"shared" variable.
(In my application, it is sometimes the case that it doesn't know to
load a module until well after the application has gone multithreaded.)
Subject: | perl-shared.pl |
use strict;
use warnings;
use threads;
use threads::shared;
use Thread::Queue;
our $q = new Thread::Queue;
sub doload {
eval <<'EOT'
package child;
use strict;
use warnings;
use threads;
use threads::shared;
our $var : shared;
sub process {
lock($var);
$var = 0 unless defined($var);
print "$var\n";
++$var;
}
EOT
;
}
sub child {
&doload();
$q->dequeue();
child::process();
}
our @thr;
#&doload();
foreach my $i (1..5) {
push @thr, scalar threads->create('child');
}
&doload();
foreach my $i (1..5) {
$q->enqueue($i);
}
foreach my $t (@thr) {
$t->join();
}