访问atomic< int>的C ++ 0x作为非原子 [英] Accessing atomic<int> of C++0x as non-atomic

查看:136
本文介绍了访问atomic< int>的C ++ 0x作为非原子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的程序中有一个原子变量 atomic< int> 。在某些地方,我不需要原子地访问它的值,因为我只是检查它的0是否。换句话说,在那些实例中,我想避免在有原子访问时发生的总线锁定等的开销。

I have an atomic variable in my program of type atomic<int>. At some places I don't need to access the value in it atomically, as I just check if its 0 or not. In other words, at those instances I want to avoid the overhead of bus locking etc. that happens when there is atomic access.

如何以非原子方式访问原子变量。是类型转换与(int)足够,像如下?如果没有,我想我该怎么做呢?

How can I access the atomic variable non-atomically. Is typecasting it with (int) enough, like as follows? If not, which I think, how can I do this?

atomic<int> atm;
int x;
........
x = (int)atm; // Would this be a non-atomic access, no bus locking et all?


推荐答案

你不能摆脱atomicity属性。但你可以通过放松内存排序保证来减少涉及原子变量的一些开销。

You can't get rid of the atomicity property. But you might be able to reduce some of the overhead involved in the use of atomic variables by relaxing the memory ordering guarantees.

std::atomic<int> a;

int value = a.load(std::memory_order_relaxed);
if(value == 0) {
    // blah!
}

我不建议这样做,你要避免这样。你确定你为支付这种黑客的原子操作支付了足够高的成本,并且可能引入线程错误是值得的吗?

I wouldn't recommend doing this however, and I echo all the comments urging you to avoid this. Are you sure that you're paying a high enough cost for the atomic operations that doing this hack and potentially introducing threading bugs is worth it?

这篇关于访问atomic&lt; int&gt;的C ++ 0x作为非原子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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