Search code examples
multithreadingperlmultiprocessormemory-visibility

Perl ithreads :shared variables - multiprocessor kernel threads - visibility


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?


Solution

  • 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.)