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]
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.
"Certainly avoid yourself. He is a newbie and might not realize it. You'll hate his code deeply a few years down the road." - Sortie
[ My OS ] [ VDisk/SFS ]
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.
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.