Do you know the keyword volatile in C language?

Publisher:幸福如愿Latest update time:2019-11-21 Source: 51hei Reading articles on mobile phones Scan QR code
Read articles on your mobile phone anytime, anywhere

When we learn the 32 keywords of C language, we don't pay much attention to the keyword volatile. Volatile is a type modifier. The Chinese meaning of volatile is "changeable". So when do we use it in the program? We often see the use of this keyword when analyzing the kernel. For example:

view plaincopy to clipboardprint?
1.struct task_struct {  
2.volatile long state; /* -1 unrunnable, 0 runnable, >0 stopped */  
3.void *stack;  
4.atomic_t usage;  
5.unsigned int flags; /* per process flags, defined below */  
6.unsigned int ptrace;  
7........  
struct task_struct { volatile long state; /* -1 unrunnable, 0 runnable, >0 stopped */ void *stack; atomic_t usage; unsigned int flags; /* per process flags, defined below */ unsigned int ptrace; .......

In the application, volatile is mainly designed to modify variables that are accessed and modified by different threads.

The volatile variable means that the variable may be changed unexpectedly, so the compiler should not perform corresponding optimizations. To be precise, the optimizer must carefully re-read the value of this variable each time it is used, rather than using the copy stored in the register.

For example:

extern int a; // Statement 1 Assume that a is a global variable

......

int b=a; //Statement 2

int c=a; //Statement 3

The value of a is used in both statement 2 and statement 3. When the optimizer references the value of a in statement 3, it assumes that the value of a has been read into the register in statement 2, and a has not been modified between statement 2 and statement 3. Therefore, there is no need to read the value of a from the memory, so the value in the register is used directly. However, if an interrupt occurs before statement 3 is executed, and the interrupt happens to modify a, then the value retrieved by statement 3 will be problematic.


If the global variable a above is modified as volatile, the optimizer cannot optimize statement 3 and must retrieve the value from the memory.

Reference address:Do you know the keyword volatile in C language?

Previous article:Study Notes - S3C2440 Memory Manager
Next article:Samsung S3C2440 GPIO output driver LED

Latest Microcontroller Articles
Change More Related Popular Components

EEWorld
subscription
account

EEWorld
service
account

Automotive
development
circle

About Us Customer Service Contact Information Datasheet Sitemap LatestNews


Room 1530, 15th Floor, Building B, No.18 Zhongguancun Street, Haidian District, Beijing, Postal Code: 100190 China Telephone: 008610 8235 0740

Copyright © 2005-2024 EEWORLD.com.cn, Inc. All rights reserved 京ICP证060456号 京ICP备10001474号-1 电信业务审批[2006]字第258号函 京公网安备 11010802033920号