Subj : Re: Concurrent write undefined? To : comp.programming.threads From : David Schwartz Date : Mon May 23 2005 01:06 pm "Jonas Latt" wrote in message news:4291886f$1@nntp.unige.ch... > I have a question on the memory model underlying the pthread library (I am > programming in C++ with pthreads on a Linux platform). Do you want what you are guaranteed? Or what happens to happen on that platform? > In the code I am concerned about, several threads write concurrently to > the same shared variable (I am implementing the PRAM version of a > quicksort. In this model, all threads write their ID to the same location, > in order to determine in a random way the next pivot). My question is: do > I need to protect this shared variable by a Mutex? Or is the result > undefined if I don't? I am of course aware that the result is undefined in > the sense that it is unpredictable which thread wins the race and writes > the number which will finally be contained in the shared variable; this is > actually a desired side-effect of the algorithm. But do I at least have > the guarantee that the operation results in that a well-defined number > (one of those proposed by the threads) is written to the shared variable, > or do I have completely undefined behavior? You have completely undefined behavior. > When I implement it, the algorithm works well without Mutex. But I doubt > that what I am doing is portable or even reproducible. Can anybody give me > a hint on this? Does the answer to this kind of questions depend on the > thread library? Or the programming language? Or the hardware? I would also > be very grateful for a pointer to some literature on these issues. This sounds like a really strange "optimization". If you want a random number, why not just use a reasonable random number generator? DS .