Subj : Re: stl & threads To : comp.programming.threads From : Uenal Mutlu Date : Wed May 25 2005 06:10 am "David Schwartz" wrote > > "Uenal Mutlu" wrote > > [snip] > > > bool IsLockedByAny() const { return cLocked > 0; } > > bool IsLockedByMe() const { return cLocked > 0 && dwThrId == > > GetCurrentThreadId(); } > > [snip] > > > private: > > CRITICAL_SECTION cs; > > size_t cLocked; > > DWORD dwThrId; > > const bool fRecursiveMutex; > > }; > > [snip] > > Suppose I write code like this: > > while(IsLockedByAny() && !IsLockedByMe()) i++; > > What guarantees that the compiler doesn't optimize away the repeated > reads of 'cLocked' and spin forever? I admit that it's dumb to do something > like that, but it's also bad for a mutex class to contain errors. Yeah, a good argument. The solution is to make them volatile: volatile size_t cLocked; volatile DWORD dwThrId; .