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

if i create a queue and pass it as parameter to a thread like

my $q = new Thread::Queue; my $thr = threads->new(\&thr_func, $q); sub thr_func{ my ($queue) = @_; }

is this queue passed as a reference or rather is $q from main block a reference to the queue (as it is created with 'new' keyword)?

Replies are listed 'Best First'.
Re: creating thread : are parameter objects passed via reference ?
by ELISHEVA (Prior) on Jul 15, 2009 at 10:09 UTC

    Perl parameters are passed by reference - see perlsub. However, when you do

    my ($param1, $param2) = @_

    $param1 and $param2 get a copy of each element in @_, effectively turning a pass by reference into a pass by value. If you need to access the original variable passed in rather than a copy of its value, you can use $_[0], $_[1], etc.

    But I don't think passing by reference vs. value is much of an issue in the code sample above. Perl "objects" are references in their own right. If you pass $q to your function, then $queue and $q both point to the same object, not a copy of each other.

    Additionally, new isn't a key word in Perl. It is a method that must be defined for each class. new Thread::Queue is simply a different spelling for Thread::Queue->new(). There is nothing magical about the name "new" that turns it into a constructor. It acts like a constructor because, by convention, this method returns a blessed reference to some data that it declared and initialized. For more information on Perl's approach to objects, please see perltoot and perlobj. You may also want to take a look at perlref for a better understanding of references in Perl.

    All the above applies to function calls and variables within a thread. In Perl, all variables are, by default, thread local (see thread). Passing references between threads will cause thread death unless the data is explicitly marked as shared - see threadtut and threads::shared for more information.

    Best, beth

      ok i tried it out : used a hash in the main block and passed a reference of it to the thread => the thread gets always a whole new hash regardless i pass a ref or the hash itself !
Re: creating thread : are parameter objects passed via reference ?
by BrowserUk (Patriarch) on Jul 15, 2009 at 15:26 UTC

    If you want to share data between threads (without copying), then mark it :shared using threads::shared.

    If you want to share it, say you want to share it. Simples!

    If you want to to have unshared data in one thread, but not in another thread, create the thread before you read in or otherwise populate that data. Simples too!.


    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.