Re: MSDN volatile sample
- From: Norbert Unterberg <nunterberg@xxxxxxxxxxxxxxxxx>
- Date: Fri, 28 Dec 2007 12:18:43 +0100
George schrieb:
Thanks Norbert,
What is the possible different results when we removed the volatile (even if I can not find any different result on my machine) of the MSDN sample compared with the original case when we add the volatile keyword?
The compiler could notice that in the loop in ThreadFunc1 the variable Sentinel is never changed, so it could optimize the loop from
while (Sentinel)
Sleep(0); // volatile spin lock
to something like
if (Sentinel)
for (;;)
Sleep(0);
and the loop would never end.
The volatile keyword forces the compiler to evaulate the Sentinel variable in every loop so setting Sentinel to true in ThreadFunc2 won't remain undetected.
.
regards,
George
"Norbert Unterberg" wrote:
George schrieb:
In the MSDN volatile sample,THe result may be the same with your compiler version and optimizer setting, but is is not guaranteed to work without volatile. volatile tells the compiler not to optimize the use of the variable because it could be modified at any time by something the compiler has no control over.
http://msdn2.microsoft.com/en-us/library/12a04hfd(VS.80).aspx
I do not understand what is the purpose of the sample. I have tried to remove the keyword volatile, and the result is the same. :-)
Code with a "forgotten volatile" at the right place can work for years but fail unexpected after minor unrelated code changes.
Norbert
- Follow-Ups:
- Re: MSDN volatile sample
- From: George
- Re: MSDN volatile sample
- References:
- Re: MSDN volatile sample
- From: Norbert Unterberg
- Re: MSDN volatile sample
- Prev by Date: Re: MSDN volatile sample
- Next by Date: Re: MSDN volatile sample
- Previous by thread: Re: MSDN volatile sample
- Next by thread: Re: MSDN volatile sample
- Index(es):
Relevant Pages
|