Subj : Re: Is the following code MT-safe? To : comp.programming.threads From : Dave Thompson Date : Mon Jan 17 2005 07:09 am On Wed, 05 Jan 2005 04:42:34 GMT, Joe Seigh wrote: > So one way of doing it would be something like > > while (lock != 0) {} > if (testAndSet(&lock) == true) ... > > The first statement has no so called sequence points so you'd want > volatile in that case. But you'd could inject a sequence point in Yes there is. The predicate of a while statement is a full-expression, and the end of (evaluation/execution of) a full-expression is a sequence point. C99 6.8p4, C90 6.6. Of course, as has already been pointed out, the C standard doesn't acknowledge the existence of threads and so sequence points have no defined meaning for them. > that loop and not require volatile. Volatile and sequence points > are just part the C language kludges to deal with things it doesn't > want to do properly. Thread implementers use whatever tricks work. > It doesn't mean those tricks have any formal connection to threads. > But even when a sequence point is present for a nonvolatile it only guarantees subsequent uses are "as-if" in order for a single (nonthreaded, nonshared with anything external) program, since that's all the C standard considers. For volatile it should guarantee "accesses" are actually done, in the specified order, but 6.7.3p6 leaves "what constitutes an access ... implementation-defined", so whether this works for multithreading, even partially, is uncertain -- and for pthreads what does work is the synchronization provided by specified pthreads calls (even) _without_ volatile. > Note that the above code only works for platforms with strongly > coherent memory. On other platforms you might need something completely > different. So volatile doesn't even have any meaning with respect > to portability either. > Right. Except I would say volatile does have some meaning, just not enough to rely on. - David.Thompson1 at worldnet.att.net .