Next 3.1 Perl thread caveats Prev

Perl thread caveats

Shared variables are implemented using a Tie mechanism.

When use threads::shared; line is present, one more hidden thread is added to the application, it contains all final values of shared variables.

Consider this program. If we omit lock() call, it does not produce the expected 100000 on slow machines:

use threads (); use threads::shared (); my $count : shared = 0; my @threads; push @threads, threads->new(sub { for (1..10000) { lock($count); $count++ } }) for 1..10; $_->join foreach @threads; # wait for all threads to finish print "count = $count\n";

This is because the "++" operator is not atomic for tied variables, it is equivalent to FETCH, "+1", STORE.

Additionally, you can't share already tied variables, but you may use Thread::Tie module for this.

Next Perl Threads Prev