I need to have atomic variables in my program. Previously I was using std::atomic<int>
, but the platform in which I'm working now does not have a g++ compiler that supports C++0x. I used volatile int
and it seems to be working, as I haven't experienced a race condition yet in the multicore system I'm testing it on.
My question is if volatile int
is atomic like std::atomic<int>
? Also, does it creates memory barriers (which I also require)?
No. volatile
has nothing to do with multithreading. It doesn't enforce a memory barrier (although some compilers might choose to add that anyway), and it makes no guarantees about read/write reordering with respect to non-volatile objects.
volatile
was added to support writing to memory-mapped hardware I/O registers, and such cases, where it is important that your write isn't optimized away, but no precise ordering guarantees wrt. non-volatile reads/wrties are required.
You might also want to read this
Volatile variables do NOT imply memory barriers, and do not have the exchange
or compare_exchange_*
operations of std::atomic
. They do avoid the compiler lifting a load into multiple loads on the machine code level (and vice versa, and similar for stores) but that's it.
You may be interested in these articles:
If you do not have std::atomic
, you may want to use boost::atomic, or use the low-level barrier and atomic-operation primitives offered by whatever compiler you're using.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With