Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: C++
Expertise: Advanced
Mar 4, 2003



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Using the Volatile Keyword to Avoid Failures

When compiling a program, the compiler adds some optimizations that may cause your application to misbehave. For example consider the following code:
// To avoid threads waiting on the critical section in vain
if (m_instance == NULL)

if (m_instance == NULL)
m_instance = new MyInstance();


The compiler may cache the second condition (m_instance == NULL) and not update the content of m_instance if it has been changed by another thread. The solution is to declare the instance with the volatile keyword. This tells the compiler to get the content of m_instance every time it is used and not cache its content.

The declaration is:
volatile MyInstance* m_instance;
Yaron Mashav
Thanks for your registration, follow us on our social networks to keep up-to-date