Prince: volatile
Description: each variable is the same as its name. Sometimes it is from the heart, and sometimes determined by external factors. Only volatile variables are like one, therefore, he gained the reputation of a prince.
Role: volatile literally means volatile and changeable. Its Rhetorical variables indicate that the value of the variable is easily changed due to external factors, the compiler is strongly requested to read the variables in the memory every time they are accessed. The above may not be very clear. For another example, if you have a friend's birthday tomorrow, you have packed the gift you want to give today. Generally, when we get up tomorrow, we no longer need to open it again to verify whether the gift exists, because we know that as long as the outer packaging of the gift has not been moved, the content should not be passive. In fact, the compiler is as smart as people, and it is easy to improve efficiency, as shown in the following example:
1 int a = 10;
2 int B =;
3 int c =;
Www.2cto.com
The compiler scanned the code and found that the first line of code assigned 10 to the integer variable a, and the value of the variable a was not changed. In the second row, obtain the value in variable a and assign it to variable B. When the value of variable a is assigned to c in the code of the third line, the compiler plays a "easy task" to improve efficiency because the CPU access speed is slow (see the register keyword ", directly assigned 10 to c.
From the above Code alone, we can see that there is no problem, just like watching the birthday gift from the outer packing. However, if the above Code runs in multiple threads, it does not change its value in the context of a thread, but we cannot ensure that the value of the variable is not changed by other threads. For example, if the birthday gift is stored in another person's place, we cannot guarantee that everything in it is still intact. Of course, this data inconsistency mechanism not only occurs in multithreading, but also exists in the device status register. For example, if the value in a status register in the NIC is 1, it indicates whether network data has arrived. The value is 1 at the current time, it cannot indicate that the value of another parameter is 1 at the next time. The value of this parameter is determined by external conditions. In this case, the compiler cannot play "easy"
To prevent the compiler from saving trouble in a similar situation, you can declare these variables as volatile. In this way, no matter whether the value of the variable is changed, each time you access the value of the variable, read from the memory and registers to ensure data consistency.
Column of the author mr_raptor