Re: MSDN volatile sample
On Sat, 29 Dec 2007 23:29:00 -0800, George
<George@discussions.microsoft.com> wrote:
Hi Alexander,
I throught it is not the 1st time you mentioned Sleep(0) will prevent
compiler to optimize the code. :-)
Do you have any in-depth analysis about how Sleep(0)'s internal mechanism
prevents compiler to optimize read operation? I think some people will be
interested if you could provide some internal perpective analysis beyond the
conclusion.
It is the fact the compiler has no knowledge of Sleep's internal mechanism
that prevents the optimization. When dealing with an "opaque function" such
as this, the compiler must assume global variables are reachable from it,
which means the function may read or write the variables. Note that this
consideration applies to single-threaded code, too, and multithreading
doesn't really add anything new to it. Indeed, it's rather fortunate that
the inability to optimize access to shared data around calls to opaque
functions helps satisfy the desired memory visibility rules for mutex
lock/unlock and other synchronization operations, as long as they are
opaque. If the operations aren't opaque, the compiler has to be notified
somehow that it is not safe to optimize access to shared data across calls
to them; this could be accomplished with some mark-up mechanism along the
lines of VC's __declspec.
--
Doug Harrison
Visual C++ MVP