Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an equivalent of Java 'volatile' in C++?

In Java, sometimes when accessing the same variable from different threads, each thread will create its own copy of the variable, and so if I set the value of the variable in one thread to 10 and then I tried to read the value of this variable from another thread, I will not get 10 (because the second thread is reading from another copy of the variable!).

To fix this problem in Java, all I had to do is to use the keyword volatile, for example:

volatile int i = 123;

Does this problem also exists in C++? If so, how can I fix it?

Note: I am using Visual C++ 2010.

like image 512
paul Avatar asked Jun 17 '15 13:06

paul


People also ask

What is the volatile keyword in C?

A volatile keyword in C is nothing but a qualifier that is used by the programmer when they declare a variable in source code. It is used to inform the compiler that the variable value can be changed any time without any task given by the source code. Volatile is usually applied to a variable when we are declaring it.

Where volatile variables are stored in C?

on an AVR, both will probably be stored in SRAM. On an ARM, the volatile will be stored in SRAM and the const will probably be stored in flash. This is mainly because the AVR flash is not accessible as "normal memory" to C programs, and you can't put any variables there.

What is difference between static and volatile in C?

A static variable refers to a class variable that's shared among all instances. volatile: Volatile variables are those which are read and written to main memory. They aren't stored in local cache and are always fetched from main memory.

What does volatile mean C++?

volatile means two things − - The value of the variable may change without any code of yours changing it. Therefore whenever the compiler reads the value of the variable, it may not assume that it is the same as the last time it was read, or that it is the same as the last value stored, but it must be read again.


1 Answers

Yes, the same problem exists in C++. But since C already introduce the keyword volatile with a different meaning (not related to threads), and C++ used they keyword in the same way, you can't use volatile in C++ like you can in Java.

Instead, you're probably better off using std::atomic<T> (or boost::). It's not always the most efficient alternative, but it's simple. If this turns out to be a bottleneck, you can relax the std::memory_order used by std::atomic.

Having said that about standard C++, MSVC++ as an extension does guarantee that multiple threads can access a shared volatile variable. IIRC, all threads will eventually see the same value, and no threads will travel back in time. (That is to say, if 0 and 1 are written to a variable sequentially, no thread will ever see the sequence 1,0)

like image 169
MSalters Avatar answered Oct 01 '22 04:10

MSalters