Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

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

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
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.