1

I have a variable which is shared between several threads (assuming suitable sync method is in place).

Should I define the variable as volatile?

The reason that I am asking is: Any of the following can be the answer:

yes: Since the variable can be change by a thread and other thread should be aware of it.

no: Since compiler can understand that a value for a variable is on CPU memory and it doesn't matter which thread wants to read it, compiler would take care of it.

mans
  • 17,104
  • 45
  • 172
  • 321

3 Answers3

3

If you have suitable synchronization in place, then there is no need for volatile.

If you do not have suitable synchronization in place, then volatile does not supply suitable synchronization, although in some C++ implementations it might appear to help to a greater or lesser extent.

Steve Jessop
  • 273,490
  • 39
  • 460
  • 699
0

Generally, you should only use volatile if a library API requires it (e.g. atomic operations on Windows).

There are cases in very low level programming dealing with hardware where volatile can be required.

James Hopkin
  • 13,797
  • 1
  • 42
  • 71
  • I can understand why to use it in low level programming (memory mapped IO), but should I use it in library API? Any sample or reference? – mans Nov 20 '13 at 13:36
  • @mans: You should not use when you design your own API's. – MSalters Nov 20 '13 at 13:42
0

volatile is (nearly) useless for a multithreaded application programming. It was intended for use when interfacing with memory-mapped hardware. Although C++ Standard is silent about volatile in terms of Acquire or Release semantics on variables some specific platforms however do add additional functionality or restrictions to what volatile does. For example, in Windows 2010 (at least) Acquire and Release semantics do apply to certain operations on volatile variables:

Microsoft Specific

Objects declared as volatile are not used in certain optimizations because their values can change at any time. The system always reads the current value of a volatile object at the point it is requested, even if a previous instruction asked for a value from the same object. Also, the value of the object is written immediately on assignment. When optimizing, the compiler must maintain ordering among references to volatile objects as well as references to other global objects. In particular,

A write to a volatile object (volatile write) has Release semantics; a reference to a global or static object that occurs before a write to a volatile object in the instruction sequence will occur before that volatile write in the compiled binary.

A read of a volatile object (volatile read) has Acquire semantics; a reference to a global or static object that occurs after a read of volatile memory in the instruction sequence will occur after that volatile read in the compiled binary.

http://msdn.microsoft.com/en-us/library/12a04hfd%28v=vs.100%29.aspx

4pie0
  • 29,204
  • 9
  • 82
  • 118