Subj : Re: stl & threads To : comp.programming.threads From : David Schwartz Date : Tue May 24 2005 11:14 pm "Uenal Mutlu" <520001085531-0001@t-online.de> wrote in message news:d70ptf$nqj$05$1@news.t-online.com... >> 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; That is not *guaranteed* to work, although it happens to (at least on every possible incantation of a platform that has Win32 critical sections that exists today). The 'volatile' keyword does not force any memory barriers or any other type of inter-CPU synchronization. DS .