Subj : Re: Memory visibility with Pthreads To : comp.programming.threads From : Maciej Sobczak Date : Thu Aug 11 2005 10:02 am David Schwartz wrote: >>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. Yes, but isn't it OK for the platform (compiler+CPU+memory+...) to reorder actions performed by thread 1 so that A = 10; is done after unlock? Something like this: lock B = 10; unlock A = 10; In other discussions about this issue it was usually stressed that writes cannot be moved *from inside to outside* of the critical section embraced by lock+unlock. I got an impression that it is always OK for the platform to move "outer" writes *into* the section, which here would mean this: lock A = 10; B = 10; unlock Is it allowed? But is it allowed also to reorder the critical section with regard to other outer writes? If yes, then the answer to the OP's question is no - there is nothing that guarantees anything about the value of A when it's read in thread 2. But if it is not allowed to move A=10; from before lock to after unlock, then it means that lock and unlock are not really in pairs with regard to memory visibility and each of them, even in separation, provides some guarantees that can be relied upon (in the OP's case, the assumption is that if lock2 is after unlock1, then everything after lock2 sees the changes from before lock1). Is that true? -- Maciej Sobczak : http://www.msobczak.com/ Programming : http://www.msobczak.com/prog/ .