Perl ithreads :shared variables - multiprocessor kernel threads - visibility

211 Views Asked by At

perlthrtut excerpt:

Note that a shared variable guarantees that if two or more threads try to modify it at the same time, the internal state of the variable will not become corrupted. However, there are no guarantees beyond this, as explained in the next section.

Working on Linux supporting multiprocessor kernel threads.

Is there a guarantee that all threads will see the updated shared variable value ? Consulting the perlthrtut doc as stated above there is no such guarantee.

Now the question: What can be done programmatically to guarantee that?

3

There are 3 best solutions below

0
On BEST ANSWER

You ask

Is there a guarantee that all threads will see the updated shared variable value ?

Yes. :shared is that guarantee. The value will be safely and consistently and freshly updated.

The problem is simply that, without other synchronization, you don't know the order of these updates.

Consulting the perlthrtut doc as stated above there is no such guarantee.

You didn't read far enough. :)

The very next section in perlthrtut explains the kind of pitfalls you do face with perl threads: data races, which is to say, application logic races concerning shared data. Again, the shared data will be consistent and fresh and immune to corruption from (more-or-less) atomic perl opcodes. However, the high-level perl operations you perform on that shared data are not guaranteed to be atomic. $shared_var++, for instance, might be more than one atomic operation.

(If I may hazard a guess, you are perhaps thinking too much about other languages' lower level threading interfaces with their cache inconsistencies, torn words, reordered instructions, and lions and tigers and bears. Perl's model takes care of those low-level concerns for you.)

1
On

You seem to be confused as to what :shared does. It makes it so a variable is shared by all threads.

A variable is indeed guaranteed to have the value it has, no matter which thread accesses it. It's a tautology, so nothing can be done to programmatically guarantee that.

5
On

Using :shared on a variable causes all threads to reference it in the same physical memory address, so it doesn't matter which processor/core/hyper-thread they happen to be executing in. The perlthrtut talk of guarantees is in reference to race conditions, and in short, that you need to take into account that shared variables can be modified by any thread at any time. If this is a problem you'll need to make use of synchronization functions (e.g. lock() and cond_wait()) to control access.