单调计数整数的比较安全吗? [英] Is a comparison on monotonic count integer safe?

查看:22
本文介绍了单调计数整数的比较安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在多线程环境中这样做是不安全的:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆