当前位置:网站首页>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
边栏推荐
猜你喜欢
在visual stdio中运行qt程序
QT icon application
记第一次使用阿里字体图标库
三极管原理及特性分析
[UDS unified diagnostic service] II. Network layer protocol (1) - overview and functions of network layer
基于VGG卷积神经网络的图像识别代码实现
CUDA project encountered a series of compilation problems after changing the environment (computer)
HDU-Tunnel Warfare
【UDS统一诊断服务】一、诊断概述(1)— 诊断概述
FOC SVPWM函数PWMC_SetPhaseVoltage解析
随机推荐
记第一次使用阿里字体图标库
汇编 32位无符号加法计算器
Multibyte and Unicode in VS
日志写法(带时间)
TP download folder, compress folder and download
Introduction to nonparametric camera distortion model
Qt 给应用程序加图标
2022LDU寒假训练-程序补丁
基于VGG对五种类别图片的迁移学习
C语言进阶要点笔记2
WMI技术介绍和应用
Principle and characteristic analysis of triode
【UDS统一诊断服务】一、诊断概述(1)— 诊断概述
[UDS unified diagnostic service] II. Network layer protocol (1) - overview and functions of network layer
[UDS unified diagnosis service] i. diagnosis overview (3) - ISO 15765 architecture
MOS管特性和导通过程
[ThreadX] ThreadX source code reading plan (I)
Eigen 学习总结
Collection of practical tips for C language (continuously updated)
【UDS统一诊断服务】(补充)五、ECU bootloader开发要点详解 (2)