[Israel.pm] Lexical veriable copyed with new thread

Shmuel Fomberg semuelf at 012.net.il
Mon Dec 24 10:12:03 PST 2007

Hi All.

So the answer is that it's a feature, not bug. :-)
When a new thread is created, *everything* is copied. Including lexicals for
the calling functions.
It does make some sense, because package functions like CLONE need not
distinguish between objects. All the objects are copied.

On the other hand, objects that where masked using 'local', will not be
copied. And that breaks the make sense that I had in the last sentence.

If we change the run_test function to:
---- start code
our $x;
sub run_test {
    local $x = bless {Name=>"Haim1"}, 'Obj';
    my $y = bless {Name=>"Haim2"}, 'Obj';
        local $x = bless {Name=>"Moshe1"}, 'Obj';
        my $y = bless {Name=>"Moshe2"}, 'Obj';
---- end code

We will get the following output:
Object Obj=HASH(0x18cc01c) whose name is Haim2 Destroyed from thread 1
Object Obj=HASH(0x18cc040) whose name is Moshe2 Destroyed from thread 1
Object Obj=HASH(0x18c4cc8) whose name is Moshe1 Destroyed from thread 1
Object Obj=HASH(0x18302f0) whose name is Moshe2 Destroyed from thread 0
Object Obj=HASH(0x226d74) whose name is Moshe1 Destroyed from thread 0
Object Obj=HASH(0x226cfc) whose name is Haim2 Destroyed from thread 0
Object Obj=HASH(0x226c00) whose name is Haim1 Destroyed from thread 0

You can see that Haim1 was not copied. However the order of release is still
mystery for me...

Happy Coding

>-----Original Message-----
>From Shmuel Fomberg
>Sent: Saturday, December 22, 2007 8:04 PM
>Hi All.
>Please observe to following program:
>--- Start Code
>#!/usr/bin/perl -w
>use strict;
>use threads;
>sub thr {
>    print "Thread running.. Done.\n";
>sub run_test {
>    my $x = bless {}, 'Obj';
>    threads->create(\&thr)->join();
>sub Obj::DESTROY {
>    print "Destroyed from thread ", threads->tid, "\n";
>--- End Code
>The output that I get is:
>Thread running.. Done.
>Destroyed from thread 1
>Destroyed from thread 0
>It is clear the $x was copied to the new thread, and destroyed when it
>But why? $x is not a global, and not passed as parameter to the thread's
>entry point. Why Perl copy it?
>Sometimes I think that I don't understand anything at all... T_T
>Perl mailing list
>Perl at perl.org.il
>No virus found in this incoming message.
>Checked by AVG Free Edition.
>Version: 7.5.516 / Virus Database: 269.17.6/1192 - Release Date: 21/12/2007

More information about the Perl mailing list