Re: Will Modern C++ Design ever get fixed? Organization: unknown
?"Leigh Johnston" <email@example.com> wrote in message
?"Andre Kaufmann" <firstname.lastname@example.org> wrote in message
On 04.10.2010 22:30, Vladimir Jovic wrote:
Andre Kaufmann wrote:
On 03.10.2010 09:11, Mathias Gaunard wrote:
On Oct 2, 3:03 pm, Witold Kuzminski<witold.kuzmin...@gmail.com>
Note that with MSVC, however, volatile does do memory barriers; but
other compilers don't do it, and the C++0x standard, which provides
full support for multithreading, doesn't either.
I don't think volatile does do memory barriers in MSVC.
It "simply" prevents the compiler from doing register optimizations,
which might be relevant for multithreading.
How are volatile relevant for multithreading?
It prevents (for example under MSVC) register optimization:
Thread#1: while (!signal);
Thread#2: signal = true
Will commonly fail without marking signal volatile (under MSVC) - since
will be register optimized (commonly).
Additionally volatile prevents compiler reordering of read/write access
Don't know for sure, if it's relevant for other C++ compilers too ?
I tried to come up with a contrived example such as the one you give on
VC++9 and determined that the optimizer was clever enough such that
volatile made no difference to the assembler output. The mere presence of
library function calls seems to ensure that volatile is not necessary and
it is not possible to start a thread without a library function call. I
only spent a couple of hours investigating this however so there could
potentially still be a case where volatile is useful in VC++ at least
(particularly to stop compiler (not CPU) reordering).
My reply was slightly unclear, the following code snippet clarifies it I hope:
static DWORD WINAPI thread_proc(LPVOID aThreadableObject)
::Sleep(1000); // wait for a second
bool* p = (bool*)aThreadableObject;
*p = false;
bool gotOne = false;
bool b = false; // not volatile
HANDLE thread = ::CreateThread(NULL, 0, thread_proc, &b, 0, NULL);
b = true;
gotOne = true;
rand(); /* any (library) function which the optimizer cannot analyze seems to
a wait on the thread or some mutex locking would be less contrived */
std::cout << "volatile not needed";
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]