Turn: About the instructions and tests of the volatile keyword

xiaoxiao2021-03-05  24

Description and test of about volatile keyword: September eagles

The volatile keyword is a type modifier that uses its declared type variable representation that can be changed by some compilers, such as operating systems, hardware, or other threads. If this keyword declared variable, the compiler will no longer optimize the code to access the variable, so that stable access to special addresses can be provided. Examples of using this key are as follows:

Int Volatile NVINT;

When the value of the variable declared using the Volatile declaration, the system always re-reads data from its memory, even if its instructions have just read data from the point. And the read data is immediately saved. E.g:

Volatile INT i = 10;

INT a = i;

...

/ / Other code, did not clearly tell the compiler, to operate I

INT b = i;

Volatile indicates that I can change at any time. When using it, you must read from the address of i, so the assembly code generated by the compiler will re-read data from the address of i. The optimization method is that since the compiler found that the code between the code from the i-read data did not perform the operation, it automatically placed the last read data in B. Instead of re-reading. This way, if i is a register variable or indicates that a port data is easily error, so Volatile can guarantee stable access to special addresses. Note that in VC6, the general debug mode does not perform code optimization, so this keyword does not see. By inserting assembly code, testing there is no volatile keyword, impact on the final code: First, build a Win32 Console project with ClassWizard, insert a Voltest.cpp file, enter the following code:

#include

void main ()

{

INT i = 10;

INT a = i;

Printf ("i =% d / n", a);

/ / The role of the following assembled statement is to change the value of I in memory, but do not let the compiler know

__ASM {

MOV DWORD PTR [EBP-4], 20H

}

INT b = i;

Printf ("i =% d / n", b);

}

Then, run the program in the debug version mode, the output is as follows:

i = 10

i = 32

Then, run the program in the Release version mode, the output is as follows:

i = 10

i = 10

The results of the output show that in Release mode, the compiler optimizes the code, and the correct I value is not output for the second time. Below, we add the statement of i with the volatile keyword to see what changes:

#include

void main ()

{

Volatile INT i = 10;

INT a = i;

Printf ("i =% d / n", a);

__ASM {

MOV DWORD PTR [EBP-4], 20h

}

INT b = i;

Printf ("i =% d / n", b);

}

Run the program in the debug version and the release version, and the output is:

i = 10

i = 32

This shows that this keyplay has played its role! iWaswzq at 2004/12/4/16: 15

转载请注明原文地址:https://www.9cbs.com/read-35282.html

New Post(0)