为什么volatile存在? [英] Why does volatile exist?

查看:169
本文介绍了为什么volatile存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

volatile 关键字有什么作用?在C ++中,它解决了什么问题?



在我的例子中,我从来没有故意需要它。

volatile



我曾经在多处理器系统中使用双端口RAM。我们使用硬件管理的16位值作为信号量来知道另一个人是什么时候完成。基本上我们这样做:

  void waitForSemaphore()
{
volatile uint16_t * semPtr = WELL_KNOWN_SEM_ADDR; / *知道地址到我的信号量* /
while((* semPtr)!= IS_OK_FOR_ME_TO_PROCEED);
}

没有 volatile 优化器看到循环是无用的(这家伙从来没有设置值!他是坚果,摆脱的代码!)和我的代码将继续,而没有获取信号量,导致问题。


What does the volatile keyword do? In C++ what problem does it solve?

In my case, I have never knowingly needed it.

解决方案

volatile is needed if you are reading from a spot in memory that, say, a completely separate process/device/whatever may write to.

I used to work with dual-port ram in a multiprocessor system in straight C. We used a hardware managed 16 bit value as a semaphore to know when the other guy was done. Essentially we did this:

void waitForSemaphore()
{
   volatile uint16_t* semPtr = WELL_KNOWN_SEM_ADDR;/*well known address to my semaphore*/
   while ((*semPtr) != IS_OK_FOR_ME_TO_PROCEED);
}

Without volatile, the optimizer sees the loop as useless (The guy never sets the value! He's nuts, get rid of that code!) and my code would proceed without having acquired the semaphore, causing problems later on.

这篇关于为什么volatile存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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