Re: MSDN volatile sample
- From: George <George@xxxxxxxxxxxxxxxxxxxxxxxxx>
- Date: Fri, 28 Dec 2007 03:34:02 -0800
Thanks Norbert,
while (Sentinel)
Sleep(0); // volatile spin lock
I think even if the original code will result in deadlock. In the original
MSDN sample, Sleep(0) will sleep forever until there is a signal sent to the
sleeping thread. But in the original sample, there is no way to trigger the
thread from waking up.
The sample works by chance because Sentinel happened to false when we enters
whle loop.
Any comments? If I am wrong, please feel free to correct me. :-)
regards,
George
"Norbert Unterberg" wrote:
.
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
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. :-)
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.
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: ajk
- Re: MSDN volatile sample
- References:
- Re: MSDN volatile sample
- From: Norbert Unterberg
- Re: MSDN volatile sample
- From: Norbert Unterberg
- Re: MSDN volatile sample
- Prev by Date: Re: MSDN volatile sample
- Next by Date: The 10 richest players in “ Microsoft.Public.VC.Language ”.
- Previous by thread: Re: MSDN volatile sample
- Next by thread: Re: MSDN volatile sample
- Index(es):
Relevant Pages
|