There’s an article about semaphores on OS X. The author tests the semaphore by incrementing and decrementing a static variable in two threads. With semaphore guarding the variable access, the variable ends up being zero. Without the guard the variable ends up having some bogus value. I tried the code and it works. What I don’t understand is how may the concurrent access from the two threads make a difference in the final variable value. After all it seems to me like a bunch of +1s and –1s that should be comutative, right? I feel I am missing something glaring obvious, what is it? 🙂
Share
The problem is that
++/--are not atomic. They are essentially three operations:So if two threads load value simultaneously and store it also simultaneously. Difference will be 1 instead of 2.
Here is sample