Subj : Re: Concurrent write undefined? To : comp.programming.threads From : Joe Seigh Date : Mon May 23 2005 07:40 am On Mon, 23 May 2005 07:33:01 +0200, Jonas Latt wrote: > Dear all > > I have a question on the memory model underlying the pthread library (I > am programming in C++ with pthreads on a Linux 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? > > 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. int is probably atomic. Theres some atomic types defined in one of the Linux headers somewhere, atomic.h IIRC. The atomicity thing for C/C++ isn't documented anywhere, it's an article of faith or some sort of secret knowlege shared only be a few Linux Illuminati. More importantly is do the threads all have to see the same value being set? If so then you need something like pthread_once or a mutex depending on whether the variable is set more than once. If the latter, you'll need some additional information to keep track of what instance you're using. -- Joe Seigh When you get lemons, you make lemonade. When you get hardware, you make software. .