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