Reputation: 13116
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);
Upvotes: 8
Views: 450
Reputation: 129374
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.
Upvotes: 11
Reputation: 254461
Usually, it doesn't make sense.
Use atomic
to allow the variable to be modified on one thread while other threads may be accessing it without explicit synchronisation.
Use volatile
to control access to unusual memory locations (such as hardware registers), where every read and write must happen in the order specified by the program. A normal variable, atomic or otherwise, doesn't usually require such control.
The two concepts are unrelated to each other. In particular, do not confuse volatile
with a keyword used in other languages to make variables atomic. In C++, volatile
has nothing to do with thread interactions whatsoever.
Upvotes: 4