in reply to Re: Perl thread confustion
in thread Perl thread confustion
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
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^3: Perl thread confustion
by BrowserUk (Patriarch) on Feb 15, 2013 at 07:28 UTC | |
by 7stud (Deacon) on Feb 15, 2013 at 19:20 UTC |