应该无限循环条件变量总是声明为volatile吗? [英] Should infinite loop condition variables always be declared as volatile?

查看:167
本文介绍了应该无限循环条件变量总是声明为volatile吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这种类型的代码,

while( !cond )
 ;

如果 cond 未声明为volatile,编译器可以通过缓存它在寄存器中。在这种情况下,即使 cond 设置后,while循环仍会继续。

If cond is not declared volatile, the compiler can optimize it by caching it in a register. In that case, the while loop will continue even after cond is set.

现在这是否意味着任何这种类型的变量应始终声明为 volatile ?为什么编译器不够聪明,意识到它不应该缓存这样的变量?

Now does that mean that any such kind of variable should always be declared volatile? Why aren't the compilers smart enough to realize that it should not cache such variables?

推荐答案

为什么不缓存变量?你不会在循环中改变它,所以在C的心里,它等同于 while(true);

Why would it not cache the variable? You don't change it in the loop, so it's equivalent, in C's mind, to while (true);.

也就是说,除非你的程序是多线程的,在这种情况下,变量可以在循环运行时不改变。然而,C语言不知道关于线程(更一般地,如Lundin所说,关于任何不从 main 调用的函数,或从一个函数调用 main 等),所以你必须自己使用 volatile 让C知道有事情发生了不知道。

That is, unless your program is multithreaded, in which case the variable can be changed while the loop is running and doing nothing. However, the C language doesn't know anything about threads (and more generally, as Lundin remarked, about any functions that aren't called from main or from a function called in main, etc), so you have to use volatile by yourself to let C know that something is going on that it doesn't know about.

这篇关于应该无限循环条件变量总是声明为volatile吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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