Page 1 of 1
Article about the volatile statement (C, C++)
Posted: Wed May 09, 2007 1:39 pm
by TomTom
Since I've often encountered code that is potentially flawed when compiled with optimizations, I decided to write an article about it in the wiki. It's something
every programmer
should know, especially everyone who writes an OS. Even if compiling with optimizations is not planned in the near future
Here's the article: [wiki]Volatile_(keyword)[/wiki]
Hope it's useful/helpful
Posted: Wed May 09, 2007 2:38 pm
by Combuster
While the volatile keyword is just one way to deal with the compiler, it is by no means an end, and it is not even an guarantee for correct execution.
volatile can only force memory ordering by the compiler, but it can't force memory ordering by the processor. When dealing with synchronizing structures, memory reordering can break many algorithms due to reads and writes being rescheduled inside the processor. volatile can't fix this; you'd need assembly to insert serializing instructions, lock prefixes or explicit memory fences to cope.
----
On another note, please be careful when applying the 'minor edit' - it is meant for edits that do not change the informative contents, such as spellchecking or rewording sentences.
Posted: Wed May 09, 2007 10:14 pm
by TomTom
Well, of course you're right. That's however not what the article is about. The article is about compiler optimizations. To fix certain issues with optimizations made by the CPU at runtime there's memory barriers. Maybe I should dedicate another article to them.
Posted: Sat May 12, 2007 10:39 pm
by earlz
wow! no wonder a lot of my code with volatile wasn't working right!
I had no idea that
int * volatile ...
and
volatile int * ...
were any different!
*looks back at abandoned FDD code to see if polling was done wrong...*
Posted: Fri May 18, 2007 1:13 am
by Solar
In that case, check
const int *
vs.
int const *
vs.
int * const
too, becuase 1) and 2) are identical, 3) is a different thing, too...
Posted: Fri May 18, 2007 3:32 am
by TomTom
Yes, the effect of the placement of the const and volatile statement is the same, which is also mentioned in the article. At least somebody already fixed some issues
I noticed that GCC 4.x is optimizing a lot more agressively than the 3.x series. When I upgraded the build system of an operating system from 3.x to 4.x I had to find and fix a number of weird issues that were caused by the lack of or improper use of that statement. Which is the original motivation to write an article about it.