Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl shared variables atomicity and visibility

This I read from the threads::shared description:

By default, variables are private to each thread, and each newly created thread gets a private copy of each existing variable. This module allows you to share variables across different threads ... (more)

Let's say I have a shared variable like this:

my $var :shared;
$var = 10;

This means the variable exists only once for all the threads I create.


Now about atomicity and visibility:

If thread_A assigns a new value let's say 11:

$var = 11;

Is it guaranteed that thread_B (and all the other threads I might have created) will see the value 11 ? And is the assignment performed atomically ?

Or do we have like in Java first to acquire a lock and then do the assignment and to release the lock. And only threads using the same lock are guaranteed to see the updated value?

Or this behaves like volatile primitive variables in Java ?

like image 719
user2050516 Avatar asked Oct 06 '14 11:10

user2050516


1 Answers

It's always good practice to enforce atomicity in updates. Perl provides lock to allow us to do this. You can lock the variable itself - if the variable is shared with the thread, then so is the lock state.

If you update $var then the other threads will see the new value.

But you do have a potential race condition, depending on when they access it. If that's a problem - lock and if it's not... carry on.

Bear in mind that operations such as $var++ are not guaranteed to be atomic. (http://perldoc.perl.org/perlthrtut.html#Thread-Pitfalls%3a-Races)

like image 81
Sobrique Avatar answered Sep 30 '22 17:09

Sobrique