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

im using a defined hash both in the main block as in a thread too:

my %h => ( X => { num => 1, txt => 'X' }, Y => { num => 2, txt => 'Y' }, Z => { num => 3, txt => 'Z' }, ); my $thr = threads->new(\&thr_func, \%h); ...LOOP-MAIN #using the hash on in readonly mode (eg print all values from hash) ...END LOOP-MAIN sub thr_func { my ($h_ref) = @_; ...LOOP-THR #using the hash on in readonly mode (eg print all values from hash) ...END LOOP-THR }

is this thread safe if i dont modify values on the hash ?

Replies are listed 'Best First'.
Re: is a readonly hash thread safe ?
by Anonymous Monk on Jul 15, 2009 at 09:01 UTC
    It is thread safe even if you modify the hash, because each thread gets a copy. perlthrtut
      but i pass the reference to the hash as a parameter for thread create, so im using the only hash defined in the main block ?

        Even that reference is just a copy. See perlthrtut and/or threads::shared. Perl ithreads are based off the idea of the Win32 fork emulation, which is why every thread gets its own copy of (almost) everything. This likely is the only possible implementation anyway without risking lots of locks like Python has with its much maligned Global Interpreter Lock, as even reading a Perl variable means writing to shared memory (the refcount or integer slots for example) otherwise.

        No, each thread gets its own copy. Read the tutorial, it explains the basics.