问题
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? :)
回答1:
The problem is that ++ / -- are not atomic. They are essentially three operations:
- Load
- Inc/dec
- Store
So if two threads load value simultaneously and store it also simultaneously. Difference will be 1 instead of 2.
Here is sample
Thread A Thread B
Load 5 Load 5
Inc 6 Inc 6
Store 6 Store 6
来源:https://stackoverflow.com/questions/3896952/testing-a-semaphore-by-counting