I have a few questions about VOLATILE
in C++
:
- It is believed that the shared objects (Ala, a connected list, all methods of which are protected by internal mutex) do not need to do
volatile
when used from different streams. Question – why? IfVolatile
is needed to explain the compiler of the fact that the value may change unexpectedly and it is not necessary to optimize it, then why a hosted list that synchronizes access to itself, it works fine when used from different streams and without specifiervolatile
? - What is the semantics of a method that is marked by the specifier
Volatile
? - When you need to use the
volatile specifier
? An example with a loop that is controlled by the flag that changes from another stream is too simplified and when considering real scenariosC++
Clarity does not give any.
Answer 1, Authority 100%
It is believed that the shared objects (Ala, a connected list, all methods of which are protected by internal mutex) do not need to do a Volatile when used from different streams. Question – Why?
Because the synchronization primitive itself (Mutex) is a “barrier”. The topic is extensive and in one answer is not disclosed. But you can start reading here http://scrutator.me/post/ 2012 / 04/04 / Parallel-World-P1.aspx And Anthony William – book “Parallel programming on C++ in action. Practice of development of multi-threaded programs”
But if we speak in a simple language, then if one then modified different variables and let go of Mutex, and the other captured the same Mutex and tries to read the same variables, then their state will be “expected.” And without the capture of Mutex – not a fact.
What is the semantics of a method that is marked by the Volatile specifier?
Well, there are no methods in C++. There is a function of a class member, well, or just a function. And the semantics is the same as const – your this will be volatile.
When do you need to use the Volatile specifier at all? An example with a cycle that is controlled by the flag that changes from another stream is too simplified and when considering real C++ scenarios clarity does not give any.
Volatile should be used when developing drivers and microcontrollers. Based essence of Volatile reveals such an example
volatile int a;
a = 1;
a = 2;
Without a Voltile compiler just throws the first assignment. It is meaningless. And with a Voltile record will be produced twice. What for? A variable A can be associated with some external device and write to this variable will record to some kind of I / O port. And optimization will only interfere.