Subj : Re: [.NET] Volatile Fields To : comp.programming.threads From : David Hopwood Date : Mon Sep 19 2005 01:33 am Cool Guy wrote: > David Schwartz wrote: > >> There are three things that cause problems for multi-threaded programs >>on typical modern SMP machines: >> >> 1) Instruction re-ordering. This is where the compiler or the processor >>internally performs instructions in a different order from that in the >>high-level code. > > So, with this issue, the reads/writes - when they're made - *will* be made > in a way that other threads can see them -- but the only problem is that > they might happen too late or too early, right? In practice, yes. Documentation or formal descriptions of memory models sometimes don't make it clear whether, in the absence of memory barriers, writes are still guaranteed to be performed with respect to all other threads after a finite delay. But AFAIK, all implemented architectures do have this finite delay property. >> 2) Posted writes. This is where the CPU does not output a write to its >>cache immediately but instead puts it in a temporary holding place. (Not the >>L2 cache, but a posted write buffer.) >> >> 3) Speculative fetches. This is where the CPU reads data before it needs >>it and keeps the data for a later instruction. > > So I assume memory barriers solve all three problems? For almost all purposes you can assume that they do. Strictly speaking, though, adding memory barriers is not always sufficient to simulate sequentially consistent behaviour. For instance, you might think that in this example: Start with X == Y == 0. Processor 1: X = 1; Y = 1; Processor 2: if (Y == 1) { Z = 1; } Processor 3: if (Z == 1) { assert(X == 1); } the assert cannot fail (because Z = 1 can only happen after Y = 1, which can only happen after X = 1). But in some memory models, including the model used by x86 (as far as it's possible to tell from the documentation), and probably also the one used by .NET, it *is* possible for the assert to fail. This can happen no matter what memory barriers are added, and even if X and Y are volatile in the case of .NET. -- David Hopwood .