Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is volatile int in C as good as std::atomic<int> of C++0x?

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)?

like image 299
MetallicPriest Avatar asked Jul 08 '11 16:07

MetallicPriest


2 Answers

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

like image 182
jalf Avatar answered Oct 21 '22 11:10

jalf


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:

  • volatile considered harmful
  • Volatile: Almost Useless for Multi-Threaded Programming

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.

like image 33
bdonlan Avatar answered Oct 21 '22 10:10

bdonlan