C language-volatile keyword

Due to time reasons, the volatile keyword has not yet been summarized, so I will post a few good summary blogs to prevent subsequent forgetting.

1. "C language relearning-keyword volatile"

2. "The usage and meaning of volatile in C language"

3. "Detailed explanation of the volatile keyword in C"

 

The volatile keyword is needed in the following situations:

1. Hardware registers of parallel devices (such as status registers)

Memory-mapped hardware registers usually also need to add voliate, because each read and write to it may have a different meaning.     

       #define GPC1CON *((volatile unsigned int*)0xE0200080)
       #define GPC1DAT *((volatile unsigned int*)0xE0200084)
       #define GPC1PUD *((volatile unsigned int*)0xE0200088)

       2. Non-automatic variables that will be accessed in an interrupt service subroutine (Non-automatic variables)

      Since the speed of accessing registers is faster than that of RAM, compilers generally make optimizations to reduce access to external RAM, for example:

static int i=0; //i 为非自动变量
int main(void)
{
     ...
     while (1){
     //由于编译器判断在 main 函数里面没有修改过 i,因此可能只执行一次对从i到某寄存器的读操作,
     //然后每次if判断都只使用这个寄存器里面的“i副本”,导致 dosomething 永远也不会被调用。
     if (i) dosomething();
   }
}
/* Interrupt service routine. */
void ISR_2(void)
{
      i=1;
}

3. Variables shared by several tasks in multithreaded applications

When two threads need to use a variable and the value of the variable will be changed, the volatile statement should be used. The function of this keyword is to prevent the optimizing compiler from loading the variable from memory into the CPU register. If the variable is loaded into the register, then two threads may use the variable in the memory and the other in the register, which will cause the wrong execution of the program. Volatile means that the compiler must actually fetch the variable from memory every time it manipulates the variable, instead of using the value in the existing register.
 

volatile  BOOL  bStop  =  FALSE;  //bStop  为共享全局变量
(1) 在一个线程中:  
  while(  !bStop  )  {  ...  }  
  bStop  =  FALSE;  
  return;    
 
(2) 在另外一个线程中,要终止上面的线程循环:  
  bStop  =  TRUE;  
  while(  bStop  ); 

Wait for the above thread to terminate. If bStop does not use the volatile declaration, then this loop will be an infinite loop, because bStop has been read into the register, the value of bStop in the register will never become FALSE, plus volatile, the program is executing When the value of bStop is read from the memory every time, there will be no endless loop.

 

 

Guess you like

Origin blog.csdn.net/zwb_578209160/article/details/106038308