What's the difference of the usage of volatile between C/C++ and C#/Java?

c, c#, c++, concurrent-programming, java

Solution

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".

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.

Problem

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? Here is an reference of `volatile` in C/C++. Why is volatile not considered useful in multithreaded C or C++ programming?

Original source

Related problems