Access to atomic <int> for C ++ 0x as non-atomic

I have an atomic variable in my program like atomic<int> . In some places, I don’t need to access the value in it atomically, as I just check if it is 0 or not. In other words, in these cases, I want to avoid the overhead of locking the bus, etc., What happens when there is atom access.

How can I access an atomic variable non-atomically. Is typing it with (int) sufficient, for example as follows? If not, then 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? 
+4
c ++ atomic
source share
3 answers

You cannot get rid of the property of atomicity. But you can reduce some of the overhead associated with using atomic variables by weakening the guarantees of memory ordering.

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

I would not recommend doing this, but I repeat all the comments urging you to avoid this. Are you sure you pay a high enough cost for atomic operations that do this hack and potentially introduce problems with streaming loading?

+4
source share

On most platforms, reading int (especially the alignment that the stack variable will have) will be atomic, so just assigning it int will be a simple assignment.

If a variable is not accessible atomically, as described above, you still need to just assign it across to ensure that it is not half written.

those. just use atomic variable <>. Its fine and much safer.

+2
source share

I doubt this will work, since the value passed in the cast must still be obtained from the atom. I looked at the std :: atomic <int> specialization declaration , but as far as I can tell from this, and from their declaration of the std :: atomic base class, there is no access to the base variable.

There are macro questions here that should be able to tell you whether the lock is really used for your platform, although I'm not sure if they are standard or extended. In the worst case, you can simply evaluate the ATOMIC_INT_LOCK_FREE macro and see if it exists. (note: atomic<int> also handles other things, such as providing memory at appropriate boundaries, etc.), although this does not really matter for your code; it will either be or will not, and there is no definite way to access int.

It is also possible that you could just play around with it and look at the atomic one, setting it to a known value, and then checking it with a debugger or selecting its address and printing it. You can play around with this a bit and maybe figure out a way to do some kind of (non-portable, non-standard) pointer manipulation to get a pointer to that value, and then save it outside wherever you want an atomic check.

Hope you find what you need!

+1
source share

All Articles