All lexical (my) variables are local to the thread they are declared in. Unless they are: Implicitly cloned by being made closures.
Okay, here is a closure:
{ my $x = 20; sub do_stuff { print "$x \n"; } } do_stuff(); #$x has gone out of scope here --output:-- 20 #…yet the sub can still see $x
But in the following thread can the sub see $x because it closes over $x, or can the sub see $x because:
All lexical (my) variables are local to the thread they are declared in. Unless they are: Implicitly cloned because they exist in the spawning thread prior to a 'child' thread being spawned.
use threads; use threads::shared; my $x = 20; sub do_stuff{ print "$x \n"; #closes over $x (as above) } threads->create(\&do_stuff)->join(); --output:-- 20
If perl copies all the data to a thread, why doesn't the following code also output 20:
use threads; use threads::shared; sub do_stuff{ print "$x \n"; #doesn't close over $x } my $x = 20; threads->create(\&do_stuff)->join(); #perl copies $x to the thread --output:-- <blank line> #but the thread can't see $x
In reply to Re^2: Perl thread confustion
by 7stud
in thread Perl thread confustion
by mulli
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |