单调计数整数的比较安全吗? [英] Is a comparison on monotonic count integer safe?
问题描述
我知道在多线程环境中这样做是不安全的:
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.
如果 some_var 是一个计数器呢?也就是说,它只能增加,永远不会减少.那么下面的操作线程安全吗?
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.
}
如果 some_counter 是 byte 或 int32、int64 也有区别吗?
Also does it make difference if some_counter is either byte, or int32, int64?
推荐答案
如果 some_var 是一个计数器呢?也就是说,它只能增加,永远不会减少.那么下面的操作线程安全吗?
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.
如果 some_counter 是 byte 或 int32、int64 也有区别吗?
Also does it make difference if some_counter is either byte, or int32, int64?
其实没什么区别.
您应该使用 std::atomic
(或其他模板参数类型)来保证线程安全.
You should rather use a std::atomic<int>
(or other template parameter type) to guarantee thread safety.
这篇关于单调计数整数的比较安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!