Subj : Re: Avoiding synchronization (pthreads) To : comp.programming.threads From : Marcin 'Qrczak' Kowalczyk Date : Wed Mar 02 2005 09:09 pm "Joe Seigh" writes: >> If a global variable of type int is read without holding a mutex, at >> the same time as other threads may write into it (holding the mutex), >> can anything worse than getting an out-of-date value happen in practice? >> >> The variable in question counts the number of threads. It is used >> to avoid locking in case there is only one thread. There may be >> background threads terminating asynchronously which decrement the >> variable. If the first paragraph is true, I should be safe, because >> an out-of-date value can only be larger than the true value, and >> in this case I will execute an equivalent but slower code (which >> takes the mutex, so the next time the variable will be up to date). > > You'll need an acquire barrier after reading that there is only > one thread. What can happen without it? The variable is decremented asynchronously, but it is ever incremented only by the thread which does the conditional locking. So if this thread sees an out-of-date value, it can only see a too high value, and it will work correctly in this case (in particular it always does both locking and unlocking or neither). What else than seeing an out-of-date value can happen? > int has to be atomic of course. Yes. Are there architectures where one thread decrementing an int can cause another thread which doesn't use a memory barrier see the value which has nothing to do with the actual range of values of this int? -- __("< Marcin Kowalczyk \__/ qrczak@knm.org.pl ^^ http://qrnik.knm.org.pl/~qrczak/ .