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

Categories

0 votes
261 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 Answer

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...