views:

141

answers:

5

If two threads try to write to the same address at the same time, is the value after the concurrent write guaranteed to be one of the values that the threads tried to write? or is it possible to get a combination of the bits?

Also, is it possible for another thread to read the memory address while the bits are in an unstable state?

I guess what the question boils down to is if a read or write to a single memory address is atomic at the hardware level.

+5  A: 

I think this all depends on the "memory model" for your particular programming language or system.

Brian
Very much so, as depending on the sophistication of the various parts involved (language, hardware, OS, thread model, etc) then any of the scenarios are possible.
workmad3
c++ on any hardware platform
Mark
+2  A: 

These questions are fundamentals of a system or/and programming language memory model. Therefore, pick your own OS and a programming language, read the specs and you'll see.

Boris Pavlović
A: 

On a multi-processor computer, there may not be a single "value" that is read. The two threads, and the third one, may see inconsistent values. You'd need a memory barrier to ensure every thread sees the same value at this address.

Apart from that, writes are generally atomic, so it would be either one or the other of the values that have been written (or were there in the first place) that are read. You're not talking about an Alpha processor, are you?

Pascal Cuoq
A: 

One thing for sure, for a datatype of size equal to CPU Registers can never have bits in unstable state, it will be either of the two values

Neeraj
+1  A: 

In some cases the results may be just as unpredictable when the two threads are writing to different memory addresses - in particular think about C bitfield structures, as well as compiler optimisations when writing to adjacent addresses.

If you fancy a read, Boehm's paper "Threads cannot be implemented as a library" covers this and other quirks of concurrency.

SimonJ