Subj : Re: Memory visibility with Pthreads To : comp.programming.threads From : David Schwartz Date : Wed Aug 10 2005 04:59 pm "Christoph Bartoschek" wrote in message news:7ucqs2-3pc.ln1@barney.wesseling.pontohonk.de... > I am confused about memory visibility with Pthreads. Especially I am not > sure which practices are guaranteed to be safe. What does the Pthread > standard assure about visibility of memory changes? What can be taken for > granted after some of the pthread functions have been executed? Certain specific functions are guaranteed to fully synchronize memory, such as the mutex and condition variable functions. > For example I would assume that a thread which calls pthread_join can see > all changes done by the thread which is joined to the calling thread. Correct. > However what about the changes of other threads? I guess this changes are > undetermined because one does not know in which state they are. But what > happens in the following example: > > There are two global variables and a shared mutex: > > int A = 0; > int B = 0; > > Thread 1 executes the following code: > > A = 10; > pthread_mutex_lock(mutex); > B = 10; > pthread_mutex_unlock(mutex); > > Thread 2 executes another codesequence: > > pthread_mutex_lock(mutex); > if (B == 10) { > printf("The value of A is %d\n", A); > } else { > printf("B is not 10\n"); > } > pthread_mutex_unlock(mutex); > > One question is, whether it is legal to use the variable A in thread 2? > The > other question is, whether one can be sure that the value is always 10 > when > the if condition is true? Yes, the mutex functions are defined by POSIX to fully synchronize memory. > I have another question on reading shared data. For example I have an > integer which is set before the first call to pthread_create is made. > Afterwards all threads only read from this integer. Is this legal? Or does > one have to use a synchronisation mechanism? A thread is guaranteed to see any variables set by the thread that created it prior to a call to pthread_create. DS .