Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any sense to make std::atomic<> objects with the qualifier - volatile?

Tags:

c++

c++11

atomic

Is there any sense to make atomic objects with the qualifier - volatile?

Use that:

volatile std::atomic<int> i(1);

instead of:

std::atomic<int> i(1);
like image 806
Alex Avatar asked Aug 18 '13 20:08

Alex


People also ask

Does STD Atomic need volatile?

Atomic variable examples In order to use atomicity in your program, use the template argument std::atomic on the attributes. Note, that you can't make your whole class atomic, just it's attributes. }; You don't need to use volatile along with std::atomic .

What does volatile do in C++?

Volatile Keyword in C/C++ Volatile is a qualifier that is applied to a variable when it is declared. It tells the compiler that the value of the variable may change any time.

What is atomic C++?

The atomic type is implemented using mutex locks. If one thread acquires the mutex lock, then no other thread can acquire it until it is released by that particular thread.


1 Answers

No, there is absolutely no sense in making std::atomic also volatile, as inside the std::atomic, the code will deal with the possibility that the variable may change at any time, and that other processors may need to be "told" that it has changed (the "telling" other processors is not covered by volatile).

The only time you really need volatile is if you have a pointer to piece of hardware that your code is controlling - for example reading a counter in a timer, or a which frame buffer is active right now, or telling a network card where to read the data for the next packet to send. Those sort of things are volatile, because the compiler can't know that the value of those things can change at any time.

like image 91
Mats Petersson Avatar answered Sep 20 '22 04:09

Mats Petersson