11

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.

8
  • 1
    the simplest approach is std::atomic. Commented Jun 17, 2015 at 13:22
  • 1
    std::atomic is not available in VC2010. boost::atomic is an option. Commented Jun 17, 2015 at 13:25
  • 3
    Please read what volatile is (in Java). It seems you´re overestimating what it can do. And no, without volatile it is not "one copy per thread". Commented Jun 17, 2015 at 13:27
  • 1
    @DJClayworth Maybe that´s what the OP is thinking, maybe not, that´s why I wrote it in the first place (that he should read something more about it) Commented Jun 17, 2015 at 13:30
  • 2
    Well, the threadcopy problem seems solved, but still: Read about volatile in Java. It´s not a perfect solution for thread safety in any and every situation. And C++ volatile is even less. Commented Jun 17, 2015 at 13:32

1 Answer 1

8

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)

Sign up to request clarification or add additional context in comments.

20 Comments

Isn't std::atomic only available in C++11?
@paul: Yes, but that's logical because C++03 didn't even have threads.
So how can I fix this problem if I'm using Visual C++ 2010, does Windows API provide a solution?
@paul: Use boost - the C++11 solution was directly derived from Boost. Once you upgrade to an up-to-date version of MSVC, you can probably replace using boost::atomic with using std::atomic.
What if I am only using C and Windows API threads, do you know how to solve this problem?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.