Subj : Re: Memory Barriers, Compiler Optimizations, etc. To : comp.programming.threads From : Ziv Caspi Date : Sat Feb 05 2005 02:22 am "Scott Meyers" wrote in message news:MPG.1c6c8f8e5ee0d0a79897bb@news.hevanet.com... > On Thu, 3 Feb 2005 16:58:10 -0800, SenderX wrote: >> I use volatile for source code documentation only. That about how usefull >> it >> really is wrt this kind of stuff. > > So if you want to write something like this: > > int data; > bool dataIsReady; > > ... > > data = 22; // set data to communicate to other threads > dataIsReady = true; // let other threads know that they can read data > > How do you ensure that the compiler doesn't invert the order of those > assignments? The answer depends on whom you ask, and so not very helpful. Some people (Microsoft, in particular) holds that code generation of multi-threaded programs must preserve the (very loose) rules of C/C++, and so simply declaring both variables as volatile means that the code generated by the compiler will have the assignment to data precede the assignment to dataIsReady. Others (many of them on this group) contend that C/C++ is explicitly *not* about MT programs, and you can't rely on any guarantees. In any case, C/C++ provides no mechanism to prevent the processor itself from reordering, so even if you belong to the first group, you get no standard guarantees. >> What do think about this "simple" strategy??? > > It seems reasonable to me, and it's consistent with another posting I just > made. In theory, you could get arbitrarily fine-grained with the > information you pass to the compilers this way. Unfortunately, pragmas > are > defined to be inherently platform-specific, and my guess is that it'd be > very difficult to get the C or C++ committees to standardize pragmas. A > similar idea is something like Microsoft's attributes, which, oddly > enough, > might be easier push, because it's introducing something brand new rather > than changing the semantics of something that currently exists. Microsoft has already provided some guarantees here, as specified in http://www.microsoft.com/whdc/driver/kernel/MP_issues.mspx. In particular, it treats volatile reads as having acquire semantics, and volatile writes as having release semantics, so if you target CL 14 (or later), you have a solution. I've not hears of other C/C++ compilers that provide similar guarantees, which probably is more a testament to my ignorance than anything else :-) Note that the guarantees we currently provide hold only for the platforms Windows and CL run on -- x86, x64, and Itanium. We currently don't provide a guaranteed "future-proof" model for future platforms, although some of us would really like us to do so... HTH, Ziv Caspi DISCLAIMER: I work for Microsoft. Opinions expressed here are my own, and not my employer's. I don't work for the compiler team or the Windows team, and the above is my understanding of their position, which might be wrong. .