Subj : Re: Adding thread support for C... To : comp.programming.threads From : Mayan Moudgill Date : Tue Jul 19 2005 08:09 am David Schwartz wrote: > "Mayan Moudgill" wrote in message > news:11dopdc6l57sfec@corp.supernews.com... > > > >>Consider the case of >> >>acquire(&lock) >>do_something(&x) >>release(&lock) > > >>It may be perfectly legal in C for a compiler to reorder the operations >>as: >>do_something(&x) >>acquire(&lock) >>release(&lock) >>even if lock and x are declared volatile. > > >>The addition of a barrier will prohibit this (otherwise legal) reordering. > > >>Note: nothing to do with hardware, everything to do with compilers. > > > Exactly, and that's why it should not be part of the C language. The C > language should be about how you get the hardware to do things, not how the > compiler emits code. I think you're missing the point. The "abstract machine" used in the C language standard(s) to specify the behaviour of a C program a single-threaded mode. As such, a compiler is allowed to do *any* optimization that would preserve the behavior of the program when run single-threaded, even if it changes the behavior of the program when run multi-threaded. The optimization above is one such example. Lets get more concrete. Suppose we have some multi-threaded code such as: static volatile unsigned turn; static int result; void update_result( int n, int me) { while( turn != me ) { }; result += n; turn = (me+1)%NTHREADS; } Unfortunately, according to the standard [see 5.1.2.3], the compiler is free to implement this as though it were written as: result += n; while( turn != me ) {}; turn = (me+1)%NTRHEADS; OR while( turn != me ) {}; turn = (me+1)%NTHREADS; result += n; Now, in this example, the compiler reordering can be inhibited by using volatile-qualifying result. Lets look at another example: update_result(foo(), me); /* foo() is a long-running function */ The compiler is free to treat this code as though it were written: while(turn != me ) {}; result += foo(); turn = (me+1)%NTHREADS; where now the lock is going to be held for a much longer time than the programmer anticipated. > Seriously, it is a *huge* layering error to think of the language > specification as telling the compiler what to do. The compiler must do > whatever it takes to make the *platform* do what the standard requires. The > standard specifies what happens when you run the code And, unfortunately, the standard does *NOT* specify what happens when you run the code multi-threaded. So, the standard has to be modified to handle multi-threaded programs. How would you propose to do that? In particular, how would you alter the standard to prevent some of the problems shown above from occurring? > not what instructions > the compiler emits. > > DS > > .