Mike Pomraning wrote:
> This is a scoping issue, not a threads issue. Code executed via
> 'do-FILE', 'require' or 'use' cannot see the lexicals in the
> enclosing scope of the doer, the requirer or the user.
Entirely correct. The way to deal with this is to send a ref of
the shared variable to the thread for its use.
##### main.pl #####
#!/usr/bin/perl
use strict; # Always use strict and warnings!
use warnings;
use threads;
use threads::shared;
my $a :shared = 1;
require "./sub.pm";
# Create thread and send it a ref of the shared variable
threads->create(\&thr, \$a)->detach();
print("main start: a = $a\n");
sleep(4);
print("main end: a = $a\n");
exit(0);
# EOF
##### sub.pm #####
sub thr {
my $a = shift; # Get ref to shared variable
sleep(1);
print("thread start: a = $$a\n");
sleep(2);
$$a = 2;
print("thread end: a = $$a\n");
};
1;
# EOF
##### OUTPUT #####
main start: a = 1
thread start: a = 1
thread end: a = 2
main end: a = 2