Perl - common variables atomicity and visibility

I read this from the description of threads::shared :

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

Say I have a shared variable like this:

 my $var :shared; $var = 10; 

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


Now about atomicity and visibility:

If thread_A assigns a new value, say 11:

 $var = 11; 

Is it guaranteed that thread_B (and all other threads I could create) will see the value 11? And is the task performed atomically?

Or we have, for example, in Java, to first obtain a lock, and then perform an assignment and release a lock. And only threads using the same lock are guaranteed to be able to see the updated value?

Or does it behave like volatile primitive variables in Java?

+6
source share
1 answer

It is always recommended to use atomicity in updates. Perl provides a lock so we can do this. You can lock the variable itself - if the variable is shared with the stream, then this is the lock state.

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

But you have a potential race condition, depending on when they access it. If this is a problem - lock and if it does not ... continue.

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

+4
source

Source: https://habr.com/ru/post/976294/


All Articles