Is a comparison on monotonic count integer safe?

巧了我就是萌 提交于 2020-03-03 12:07:53

问题


I know in a multithread environment doing this is not safe:

if (some_var > 0) {
  // Do something.
}

Because when comparing, there might be another thread changing the value.

What if some_var is a counter. That is, it can only increment, never decreases. Then is following operation thread safe?

if(some_counter >0) {
   // Do something.
}

Also does it make difference if some_counter is either byte, or int32, int64?


回答1:


What if some_var is a counter. That is, it can only increment, never decreases. Then is following operation thread safe?

No it isn't. Incrementing isn't an atomic operation.

Also does it make difference if some_counter is either byte, or int32, int64?

It doesn't really make a difference.

You should rather use a std::atomic<int> (or other template parameter type) to guarantee thread safety.



来源:https://stackoverflow.com/questions/57603868/is-a-comparison-on-monotonic-count-integer-safe

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