当前位置:网站首页>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
边栏推荐
猜你喜欢
随机推荐
[ThreadX] ThreadX source code reading plan (I)
【UDS统一诊断服务】五、诊断应用示例:Flash Bootloader
HDU-Tunnel Warfare
Log writing method (with time)
C语言进阶要点笔记4
欢迎使用Markdown编辑器
特效案例收集:鼠标星球小尾巴
JS高频面试题
Generate random number
Collection of practical tips for C language (continuously updated)
PN结、二极管原理详解与应用
Krypton binary
说说ts的心里话
Multibyte and Unicode in VS
Initialization of classes and objects (constructors and destructors)
Palindromic Primes
2022LDU寒假训练-程序补丁
客户端软件增量更新
Sdoi2009-hh Necklace
POJ-The Unique MST