llancet has asked for the wisdom of the Perl Monks concerning the following question:

It is said that while creating a new thread, all variables are cloned. So what about the shared vars? Is it actually also cloned and synchronized while being changed, or really shared between perl threads?

Replies are listed 'Best First'.
Re: What is a shared variable?
by dave_the_m (Monsignor) on Dec 29, 2009 at 11:13 UTC
    A shared variable is shared among all threads, not cloned.

    Dave.

      Thanks!
      I tried to test this, and on my machine shared version appears to take more working memory
      #!/usr/bin/perl -- use threads; use threads::shared; my $foo = 0 x ( 100 * 1024 ); share($foo); threads->create(sub { $foo.= 1 x ( 100 * 1024); })->join(); sleep 10;
        Shared variables are implemented using a system similar to tying. In each thread there is a lightweight object which when accessed, sets a lock then sets or retrieves the value stored in the "real" variable of which there is one shared across all threads. Depending on the usage, one or more threads may have a current or stale copy of the variable's value cached.

        If you shared an array of strings instead, you'd see less usage with shared array, since only one element of the array might be cached at any one time.

        Dave

Re: What is a shared variable?
by Anonymous Monk on Dec 29, 2009 at 08:09 UTC
    I think perlthrtut explanation is ok
    Note that Perl will protect its internals from your race conditions, but it won't protect you from you.
      I don't find the answer about whether a shared variable is copied while new thread created.