Your skill will accomplishwhat the force of many cannot PerlMonks

### comment on

 Need Help??

I was recently faced with a thread that used .= on a shared variable, and I wondered if that was safe. I figured I'd write up a introductory tutorial on the answer I found. For simplicity, we'll look at ++ first.

The following code outputs 400,000:

```my \$count     = 100_000;
my \$num_calls = 4;

my \$sum = 0;
sub inc { ++\$sum for 1..\$count; }

inc() for 1..\$num_calls;
print("\$sum\n");   # 400000

If you ran the 4 calls to inc in parallel, would the answer still be 400,000? Not likely, if you don't change inc.

```use threads;

my \$count     = 100_000;
my \$num_calls = 4;

my \$sum : shared = 0;
sub inc { ++\$sum for 1..\$count; }

\$_->join for map { threads->create( \&inc ) } 1..\$num_calls;
print("\$sum\n");   # 314813

That's because there is a race condition.

```+=======================+
|          CPU          |
+-----------+-----------+
+===========+===========+
| ...       |           |   T
| load \$sum |           |   i
| inc       |           |   m
+-----------+-----------+   e
|           | ...       |   |
|           | load \$sum |   |
|           | inc       |   v
|           | save \$sum |
|           | ...       |
+-----------+-----------+
| save \$sum |           |
| ...       |           |
+===========+===========+

The solution is to protect the critical section using a thread synchronization mechanism such as lock.

```use threads;

my \$count     = 100_000;
my \$num_calls = 4;

my \$sum : shared = 0;
sub inc { for (1..\$count) { lock(\$sum); ++\$sum } }

\$_->join for map { threads->create( \&inc ) } 1..\$num_calls;
print("\$sum\n");   # 400000

Whenever an transformation operation (read ⇒ manipulate ⇒ write) is performed on a shared variable, locking is needed. See threads::shared for tools to do this.

The program behind the <spoiler> below outputs results similar to the following:

```++s     sum = 233564 (expecting 400000)
s+=1    sum = 143915 (expecting 400000)
c.=l    length = 248149 (expecting 400000)
c=c.l   length = 123360 (expecting 400000)

As you can see, +=, .= and = . are also not atomic. The program can only prove that an operator isn't atomic (i.e. is interruptable). It cannot prove that an operator is atomic (i.e. is not interruptable). If you're getting the "expecting" result, try upping \$count and/or \$threads.

( keep:0 edit:6 reap:0 )

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":

• Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
• Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
• Read Where should I post X? if you're not absolutely sure you're posting in the right place.
• Posts may use any of the Perl Monks Approved HTML tags:
a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
• You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
 For: Use: & & < < > > [ [ ] ]
• Link using PerlMonks shortcuts! What shortcuts can I use for linking?

Create A New User
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (5)
As of 2020-02-19 16:09 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
What numbers are you going to focus on primarily in 2020?

Results (84 votes). Check out past polls.

Notices?