C / C ++和C#/ Java之间使用volatile的区别是什么? [英] What's the difference of the usage of volatile between C/C++ and C#/Java?

查看:366
本文介绍了C / C ++和C#/ Java之间使用volatile的区别是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在许多参考文献中发现它提到C / C ++中的 volatile 很弱并且可能在多处理器的并发环境中引起问题,但它( volatile )可以用作C#/ Java中差异CPU之间的通信机制。看来这个关键字在C#/ Java中比在C / C ++中更严格,但它们之间的区别/影响是什么?

I found it in many references which mention that volatile in C/C++ is is weak and may cause issue in concurrent environment on multiple processor, but it (volatile) can be used as communication mechanism between difference CPUs in C#/Java. It seems this keyword is more strict in C#/Java than in C/C++, but what's the difference/impact between them?

这是<$ c $的引用c> C / C ++中的volatile 。
为什么不挥发在多线程C或C ++编程中被认为有用吗?

推荐答案

对于 C#/ Java volatile 告诉编译器必须永远不要缓存变量的值,因为它的值可能会在程序本身的范围之外发生变化。然后,如果变量在其控制之外发生变化,编译器将避免任何可能导致问题的优化。

For C#/Java, "volatile" tells the compiler that the value of a variable must never be cached as its value may change outside of the scope of the program itself. The compiler will then avoid any optimisations that may result in problems if the variable changes "outside of its control".

C / C ++ 中,开发嵌入式系统或设备驱动程序时需要 volatile ,您需要读取或写入内存映射的硬件设备。特定设备寄存器的内容可能随时更改,因此您需要 volatile 关键字以确保编译器不会优化此类访问。

In C/C++, "volatile" is needed when developing embedded systems or device drivers, where you need to read or write a memory-mapped hardware device. The contents of a particular device register could change at any time, so you need the "volatile" keyword to ensure that such accesses aren't optimised away by the compiler.

这篇关于C / C ++和C#/ Java之间使用volatile的区别是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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