Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the volatile qualifier used through out std::atomic?

From what I've read from Herb Sutter and others you would think that volatile and concurrent programming were completely orthogonal concepts, at least as far as C/C++ are concerned.

However, in GCC implementation all of std::atomic's member functions have the volatile qualifier. The same is true in Anthony Williams's implementation of std::atomic.

So what's deal, do my atomic<> variables need be volatile or not?

like image 675
deft_code Avatar asked Mar 19 '10 16:03

deft_code


People also ask

What is the use of volatile qualifier?

The volatile qualifier declares a data object that can have its value changed in ways outside the control or detection of the compiler (such as a variable updated by the system clock or by another program).

Is Atomic volatile C++?

Firstly, volatile does not imply atomic access. It is designed for things like memory mapped I/O and signal handling. volatile is completely unnecessary when used with std::atomic , and unless your platform documents otherwise, volatile has no bearing on atomic access or memory ordering between threads.


1 Answers

To summarize what others have correctly written:

C/C++ volatile is for hardware access and interrupts. C++11 atomic<> is for inter-thread communication (e.g., in lock-free code). Those two concepts/uses are orthogonal, but they have overlapping requirements and that is why people have often confused the two.

The reason that atomic<> has volatile-qualified functions is the same reason it has const-qualified functions, because it's possible in principle for an object be both atomic<> and also const and/or volatile.

Of course, as my article pointed out, a further source of confusion is that C/C++ volatile isn't the same as C#/Java volatile (the latter is basically equivalent to C++11 atomic<>).

like image 54
Herb Sutter Avatar answered Oct 08 '22 14:10

Herb Sutter