在哪里使用易失性? [英] Where to use volatile?

查看:16
本文介绍了在哪里使用易失性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读到了 volatile 关键字,但我不知道应该在什么情况下使用它.

I read about volatile keyword, but I don't know in what situations I should use it.

当内存(变量)被更新而进程没有意识到这一点时?

When the memory (variable) is getting updated and process is not aware of that?

驱动程序在什么情况下应该使用 volatile 变量?

In what cases should drivers use volatile variables?

推荐答案

在我的世界中,最常见的情况是当您编写使用内存映射 I/O 的微控制器时.寄存器中的值可能会因外部数字输入而改变,但如果您不将变量声明为 volatile,编译器可能会完全优化代码,您会想知道为什么没有任何效果.

The most common case in my world is when you are programming microcontrollers that use memory-mapped I/O. The value in a register could change due to external digital inputs, but if you don't declare a variable as volatile, the compiler might optimize the code out completely and you'll be wondering why nothing works.

Matt 建议我对关于优化"代码的声明进行修饰.内存映射 I/O 在代码中通过指针访问.当您想要检查按钮的状态时,通常会将寄存器的值与按钮​​的位掩码按位与.如果你不指定 volatile,编译器会说,嘿,你的代码实际上从来没有改变那个指针的值,所以我将删除你按位与它的那个语句,因为值总是一样!".

Matt suggested that I embellish on the statement regarding code getting "optimized out". Memory mapped I/O is accessed in code via pointers. When you want to check the state of a button, you will typically bitwise AND the value of the register with the bitmask for the button. If you don't specify volatile, the compiler will say, "hey, your code never actually changes the value of that pointer, so I'm going to just remove that statement where you've bitwise ANDed it, because the value is always the same!".

希望这能澄清我的陈述.谢谢你的建议,马特.

Hopefully this clears my statement up a bit. Thanks for the suggestion, Matt.

这篇关于在哪里使用易失性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆