|No such thing as a small change|
Threads: why locking is required when using shared variablesby ikegami (Pope)
|on Oct 19, 2006 at 18:47 UTC||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:
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.
That's because there is a race condition.
The solution is to protect the critical section using a thread synchronization mechanism such as lock.
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:
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.
Update: Added the preface and links to Wikipedia.