当前位置:网站首页>The use of volatile in C language
The use of volatile in C language
2022-04-23 06:48:00 【tilblackout】
volatile Keyword means changeable , Remind the compiler to read data from the variable address , Instead of sometimes optimizing to temporarily use the value in the register . If the variable is updated by another program or function , Especially if you modify it in an interrupt , The compiler is likely to optimize variables , There will be inconsistencies .
For example, modify the value of a variable in an interrupt , But when an interrupt is triggered, the compiler doesn't know , Then the compiler will think that the code will not execute , So as to optimize . that volatile This variable tells the compiler that it is mutable , Don't optimize it .
The concept of instruction reordering :
static int num = 0;
Threads 1:
num = 2;
ready = true;
Threads 2:
if (ready)
printf("%d",num);
-----------------------------------
In two threads , There is no data dependency , Maybe threads 1 The order of execution will change to
ready = true;
num = 2;
It leads to threads 2 Output the default 0
And add volatile The key word , Will add... After the write operation store Barrier directive , Add... Before reading load barrier , Prevent instruction reordering summary :
- The variables modified in interrupt service program for other programs to detect need to add volatile;
- In a multitasking environment, the shared flag among tasks should be marked with volatile;
- Memory mapped hardware registers are usually added with volatile explain , Because every time you read and write it, it may have a different meaning ;
版权声明
本文为[tilblackout]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230549282671.html
边栏推荐
- C语言进阶要点笔记3
- Understanding of SSH public key and private key
- 说说ts的心里话
- Shell脚本 &&和||的使用
- Principle and characteristic analysis of triode
- [ThreadX] h743 + ThreadX + Filex migration record
- Interprocess communication - mutex
- 【UDS统一诊断服务】一、诊断概述(2)— 主要诊断协议(K线和CAN)
- undefined reference to `Nabo::NearestNeighbourSearch
- Matching between class template with default template argument and template parameter
猜你喜欢
随机推荐
2022ldu winter vacation training - program patch
[stepping on the pit] MELD in win11 wsl2 cannot be used normally. Problem repair
[UDS unified diagnostic service] II. Network layer protocol (2) - data transmission rules (single frame and multi frame)
Object array and object pointer
Camera calibration: key point method vs direct method
Notes on advanced points of C language 2
Assembler 32-bit unsigned addition calculator
ES6面试题(参考文档)
Makefile基础、常用函数及通用Makefile
20220222回归职场
C语言进阶要点笔记4
POJ-The Unique MST
【UDS统一诊断服务】一、诊断概述(2)— 主要诊断协议(K线和CAN)
服务器常见错误代码 总结
三极管原理及特性分析
CUDA环境安装
realsense 选型大对比D455 D435i D415 T265 3D硬件对比
Declared as a global variable
对象的动态建立和释放,赋值和复制
【UDS统一诊断服务】一、诊断概述(1)— 诊断概述




![[UDS unified diagnosis service] i. diagnosis overview (3) - ISO 15765 architecture](/img/ef/173281ffb354b9abe1b730b89469cc.png)



