Home  >  Article  >  Backend Development  >  What is the function of volatile keyword in C language?

What is the function of volatile keyword in C language?

青灯夜游
青灯夜游Original
2020-10-30 15:02:223990browse

The role of the volatile keyword in C language: to remind the compiler that the variable defined later may change at any time, so every time the compiled program needs to store or read this variable, tell the compiler about it If this variable is not optimized, the data will be read directly from the variable memory address, thus providing stable access to the special address to avoid errors.

What is the function of volatile keyword in C language?

Tutorial recommendation: "c language tutorial video"

1. Preface

1. Introduction to compiler optimization:

Since the memory access speed is far less than the CPU processing speed, in order to improve the overall performance of the machine, in the hardware Introduce hardware cache Cache to accelerate access to memory. In addition, the execution of instructions in modern CPUs does not necessarily follow a strict order. Instructions without correlation can be executed out of order to make full use of the CPU's instruction pipeline and improve execution speed. The above are hardware-level optimizations. Let’s look at software-level optimization: one is optimized by the programmer when writing code, and the other is optimized by the compiler. Commonly used methods for compiler optimization include: caching memory variables into registers; adjusting the order of instructions to make full use of the CPU instruction pipeline. A common method is to reorder read and write instructions. When optimizing conventional memory, these optimizations are transparent and very efficient. The solution to problems caused by compiler optimization or hardware reordering is to place a memory barrier between operations that must be executed in a specific order from the perspective of the hardware (or other processor). Linux provides a macro solution. Compiler execution order issues.

void Barrier(void)

This function notifies the compiler to insert a memory barrier, but it is invalid for hardware. The compiled code will store all modified values ​​​​in the current CPU register into memory. These are needed When the data is needed, read it from the memory again.

2. Volatile is always related to optimization. The compiler has a technology called data flow analysis, which analyzes where the variables in the program are assigned, where they are used, and where they fail, and the analysis results It can be used for constant merging, constant propagation and other optimizations, and can further eliminate some code. But sometimes these optimizations are not required by the program. In this case, you can use the volatile keyword to prohibit these optimizations.

2. Detailed explanation of volatile:

##1. Principle and function:

Volatile's original meaning is "volatile", because accessing registers is much faster than accessing memory units, so compilers generally perform optimizations to reduce access to memory, but dirty data may be read.

When required to use volatile to declare a variable value, the system always re-reads the data from the memory where it is located, even if the previous instruction just read it from there Data has been read.

To be precise, when encountering a variable declared by this keyword, the compiler will no longer optimize the code that accesses the variable (data will be read directly from the variable memory address ), thus providing stable access to special addresses; if volatile is not used, the compiler will optimize the declared statement. (To put it simply: the volatile keyword affects the result of compiler compilation. A variable declared with volatile means that the variable may change at any time. Do not perform compilation optimization on operations related to the variable to avoid errors)

2. Look at two examples:

1>Tell the compiler not to do any optimization

For example, if you want to send two instructions to a certain address:

int *ip =...; //设备地址 
*ip = 1; //第一个指令 
*ip = 2; //第二个指令

The above program compiler may be optimized:

int *ip = ...; 
*ip = 2;

As a result, the first instruction is lost. If you use volatile, the compiler is not allowed to do any optimization, thereby ensuring the original intention of the program:

volatile int *ip = ...; 
*ip = 1; 
*ip = 2;

Even if you want the compiler to do optimization, it will not pay twice. Value statements are reduced to one. It can only do other optimizations.

2>Variables defined with volatile will be changed outside the program and must be read from memory each time , and cannot reuse the backup placed in the cache or register.

For example:

volatile char a;
a=0;
while(!a){
//do some things;
}
doother();

如果没有 volatiledoother()不会被执行

3.下面是使用volatile变量的几个场景:

1>中断服务程序中修改的供其它程序检测的变量需要加volatile;

例如:

static int i=0;
int main(void)
{
     ...
     while (1){
if (i) dosomething();
}
}
/* Interrupt service routine. */
void ISR_2(void)
{
      i=1;
}

程序的本意是希望ISR_2中断产生时,在main函数中调用dosomething函数,但是,由于编译器判断在main函数里面没有修改过i,因此可能只执行一次对从i到某寄存器的读操作,然后每次if判断都只使用这个寄存器里面的“i副本”,导致dosomething永远也不会被调用。如果将变量加上volatile修饰,则编译器保证对此变量的读写操作都不会被优化(肯定执行)。此例中i也应该如此说明。

2>多任务环境下各任务间共享的标志应该加volatile

3>存储器映射的硬件寄存器通常也要加voliate,因为每次对它的读写都可能有不同意义。

例如:

假设要对一个设备进行初始化,此设备的某一个寄存器为0xff800000。

int  *output = (unsigned  int *)0xff800000;//定义一个IO端口;
int   init(void)
{
      int i;
      for(i=0;i< 10;i++){
         *output = i;
      }
}

经过编译器优化后,编译器认为前面循环半天都是废话,对最后的结果毫无影响,因为最终只是将output这个指针赋值为9,所以编译器最后给你编译编译的代码结果相当于:

int  init(void)
{
      *output = 9;
}

如果你对此外部设备进行初始化的过程是必须是像上面代码一样顺序的对其赋值,显然优化过程并不能达到目的。反之如果你不是对此端口反复写操作,而是反复读操作,其结果是一样的,编译器在优化后,也许你的代码对此地址的读操作只做了一次。然而从代码角度看是没有任何问题的。这时候就该使用volatile通知编译器这个变量是一个不稳定的,在遇到此变量时候不要优化。

例如:

volatile  int *output=(volatile unsigned int *)0xff800000;//定义一个I/O端口

另外,以上这几种情况经常还要同时考虑数据的完整性(相互关联的几个标志读了一半被打断了重写),在1中可以通过关中断来实现,2中禁止任务调度,3中则只能依靠硬件的良好设计。

4.几个问题

 1)一个参数既可以是const还可以是volatile吗?

可以的,例如只读的状态寄存器。它是volatile因为它可能被意想不到地改变。它是const因为程序不应该试图去修改它。

2) 一个指针可以是volatile 吗?

可以,当一个中服务子程序修该一个指向一个buffer的指针时。

5.volatile的本质:

1> 编译器的优化

在本次线程内, 当读取一个变量时,为提高存取速度,编译器优化时有时会先把变量读取到一个寄存器中;以后,再取变量值时,就直接从寄存器中取值;当变量值在本线程里改变时,会同时把变量的新值copy到该寄存器中,以便保持一致。

当变量在因别的线程等而改变了值,该寄存器的值不会相应改变,从而造成应用程序读取的值和实际的变量值不一致。

当该寄存器在因别的线程等而改变了值,原变量的值不会改变,从而造成应用程序读取的值和实际的变量值不一致。

2>volatile应该解释为“直接存取原始内存地址”比较合适,“易变的”这种解释简直有点误导人。

6.下面的函数有什么错误:

int square(volatile int *ptr)
{
return *ptr * *ptr;
}

该程序的目的是用来返指针*ptr指向值的平方,但是,由于*ptr指向一个volatile型参数,编译器将产生类似下面的代码:

int square(volatile int *ptr)
{
int a,b;
a = *ptr;
b = *ptr;
return a * b;
}

由于*ptr的值可能被意想不到地该变,因此a和b可能是不同的。结果,这段代码可能返不是你所期望的平方值!正确的代码如下:

long square(volatile int *ptr)
{
int a;
a = *ptr;
return a * a;
}

注意:频繁地使用volatile很可能会增加代码尺寸和降低性能,因此要合理的使用volatile。

更多编程相关知识,请访问:编程教学!!

The above is the detailed content of What is the function of volatile keyword in C language?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn