HiveBrain v1.2.0
Get Started
← Back to all entries
gotchacppCritical

Why does volatile exist?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
whydoesexistvolatile

Problem

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

In my case, I have never knowingly needed it.

Solution

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.

Code Snippets

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

Context

Stack Overflow Q#72552, score: 354

Revisions (0)

No revisions yet.