Testing a semaphore by counting

对着背影说爱祢 提交于 2019-12-24 09:39:58

问题


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:

  1. Load
  2. Inc/dec
  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!