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
Article about the volatile statement (C, C++)
- Combuster
- Member
- Posts: 9301
- Joined: Wed Oct 18, 2006 3:45 am
- Libera.chat IRC: [com]buster
- Location: On the balcony, where I can actually keep 1½m distance
- Contact:
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.
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.
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.
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.