Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...