Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
282 views
in Technique[技术] by (71.8m points)

c++ - Accessing atomic<int> of C++0x as non-atomic

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.

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?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...