Volatile in Java and C++

1. Volatile in Java: In the Java memory model, threads shared resources are placed in main memory, and each thread has its own local memory at the same time. The local memory stores a copy of the main memory variables used by the thread. All operations on variables by threads must be performed in working memory, and variables in main memory cannot be directly read and written. This may result in the inability to read the latest state of variables between threads. Variables modified by volatile will be forced to write to the main memory when modified, so as to ensure the visibility of the variable to other threads.

2. Volatile in C++: In a single-task environment, inside a function body, if the statement between reading the value of the variable twice does not modify the value of the variable, then the compiler will try to modify the executable code optimize. Because the speed of accessing the register is faster than RAM (reading the value of the variable from the RAM to the register), as long as the value of the variable does not change in the future, the value of the variable will be read from the register without accessing the RAM. The variable modified by volatile will always access its value from RAM.
 

Guess you like

Origin blog.csdn.net/u012906122/article/details/103701241