Re: Will Modern C++ Design ever get fixed? Organization: unknown
On 09/10/2010 00:26, Andre Kaufmann wrote:
On 07.10.2010 19:53, Leigh Johnston wrote:
?"Leigh Johnston" <leigh@i42.co.uk> wrote in message
[...]
I tried to come up with a contrived example such as the one you give on
The code is only slightly different (have a look at the jump address)
it's hard to see the difference.
I used the following example (MSVC Windows) to check it:
volatile bool flag = false;
DWORD __stdcall SetIt(void* lpThreadParameter)
{
flag = true;
return 0;
}
int main(int argc, char* argv[])
{
QueueUserWorkItem(&SetIt, 0, 0);
while (!flag);
printf("End");
return 0;
}
The assembly code of [while(!flag)] is:
With volatile:
00831020 mov al,byte ptr [aha (833370h)]
00831025 test al,al
00831027 je wmain+10h (831020h)
Without volatile:
008F101F mov al,byte ptr [aha (8F3370h)]
while (!aha);
008F1024 test al,al
008F1026 je wmain+14h (8F1024h)
In the example without volatile, the code jumps to
008F1024 test al,al
and not to
008F101F mov al,byte ptr [aha (8F3370h)]
Since the register is never changed (without volatile) it will be an
endless loop. Simply try to execute the code with and without volatile,
you will see the difference.
Andre
Your version is different to mine as it doesn't involve calling a library
function in the loop. Your version is too contrived as such a busy loop would
be uncommon in practice (as it results in 100% CPU core usage) the common
alternative being the use of synchronization primitives, sleep() etc. I guess
we could argue all day coming up with examples and counter-examples and arguing
if said examples are realistic.
I used to be in the VC++ "use volatile" camp but I have been slowly convinced of
its superfluousness; I still have one volatile in my codebase namely the "state"
variable of my "threadable" base class and I cannot quite bring myself to remove it.
/Leigh
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]