问题
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