Subj : Re: Memory Barriers, Compiler Optimizations, etc. To : comp.programming.threads From : Joseph Seigh Date : Fri Feb 04 2005 07:52 am On Thu, 3 Feb 2005 19:37:28 -0800, Scott Meyers wrote: > From my perspective, there are two problems for C/C++ programmers: > - How do we keep compilers from ordering our reads/write in a way > contrary to what we want to be present in the generated code (i.e., > "program order")? > - How do we make sure that the reads/writes that take place during > execution are made visible to other threads in the order in which they > take place in our thread? > If compilers recognize memory barriers, memory barriers solve both > problems. If compilers do not recognize them, we may need more than memory > barriers, e.g., volatile. Volatile was defined before they knew what they were doing. It is fairly useless for the purposes of threaded programming. Even Java, which did have precise semantics for volatile w.r.t. threading, needed two tries to to give it useful semantics and from what I've heard, still doesn't have it right. [...] > > It seems clear to me that we need a way to communicate with compilers so > that they know the constraints we want to impose. They can either > recognize the signifcance of certain constructs (e.g., my understanding is > that compilers compliant with Posix threads must not optimize across > certain library calls) or we can add pragmas or something. Then again, I > could be completely off base here. I'm new to this stuff. > Posix compliance of C compilers is after the fact. C doesn't recognise threads. Adding pragmas would be the better route for compilers since neither Posix nor Microsoft have a formal definition of thread semantics. Kind of difficult to implement something if you don't know what it is. Having pragmas would shift the burden to the threading and synchronization library implementers. Plus it gets the compiler writers out of having to implement more than one set of synchronization semantics which they would have to do since they're already in widespread use. I would hate to be the compiler writer that had to tell Linus that gcc won't support the Linux kernel anymore. Linux kernel threads don't use Posix pthreads api for synchronization. These ad hoc solutions aren't as bad as you think. You just need to have an api that has well defined semantics so if you do have a problem at some point you can identify what and where the problem is. So for example, you don't want to use volatile directly even if you did think it had some useful behavior because if it did break you'd have no single point at which to fix things. You'd have to look at every single occurance of volatile, try to figure out how the programmer was trying to use it, and try to come up with an alternate fix. -- Joe Seigh .