Re: Will Modern C++ Design ever get fixed? Organization: unknown
?"Leigh Johnston" <leigh@i42.co.uk> wrote in message
news:memdnZQOHYiq6jHRnZ2dnUVZ7tmdnZ2d@giganews.com...
?"Andre Kaufmann" <akfmnews@t-online.de> wrote in message
news:i8h0nm$gf4$02$1@news.t-online.com...
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>
wrote:
[...]
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
it
will be register optimized (commonly).
Additionally volatile prevents compiler reordering of read/write access
(under MSVC).
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;
if (p)
*p = false;
return 0;
}
int main()
{
bool gotOne = false;
bool b = false; // not volatile
HANDLE thread = ::CreateThread(NULL, 0, thread_proc, &b, 0, NULL);
b = true;
while(b)
{
gotOne = true;
rand(); /* any (library) function which the optimizer cannot analyze seems to
work,
a wait on the thread or some mutex locking would be less contrived */
}
if (gotOne)
std::cout << "volatile not needed";
}
/Leigh
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]