凡使用挥发性? [英] Where to use volatile?

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

问题描述

我读到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微控制器。在寄存器中的值可能会因为外部的数字输入的变化,但如果你没有一个变量声明为挥发性,编译器可能会彻底优化code出来,你会奇怪,为什么没有任何工程。

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.

马特建议我美化上关于code得到声明优化掉了。内存映射I / O在code通过指针访问。当您想检查按钮的状态,您通常会按位与同位掩码按钮的寄存器的值。如果不指定挥发,编译器会说:嘿,你的code从来没有真正改变该指针的值,所以我打算只删除这句话,你已经按位与运算的,因为值始终是相同的!

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天全站免登陆