Take a boolean value. One thread is trying to assign a pre-determined value to it, and at exactly the same time another thread is trying to read it. What happens?
It's a race condition: one thread will win, the other will lose. Which one is not determinable in practice.
edit
Note that "winning" is not necessarily a good thing, nor is there always a guarantee that will not be corrupted (at least in general).
I believe the issue is dependent on the architecture. Without taking that into account then I always think of it in terms of a single CPU executing low level instructions and the operating system having the ability to switch out which thread is doing so at any moment. If you absolutely know that one machine instruction is what it takes to write a value and one instruction is what it takes to read a value, then I suppose there's no chance of an 'intermidiate state'.
That said, I'm not sure how what I said is complicated by multiple processors. I've always wondered actually...
Take a boolean value. One thread is trying to assign a pre-determined value to it, and at exactly the same time another thread is trying to read it. What happens?
This depends on the architecture and language in question. In practice, this typically means you'll have a race condition, and the "read" value may be the old or new value.
It's more interesting if two threads to try write to the same variable at the same time - if one writes false
and the other true
, the actual resulting variable may end up with either value.
In order to guarantee proper access, a memory barrier needs to be in place. This is especially true if dealing with multiple processors or even multiple cores, as the CPU cache lines need to be invalidated after a thread writes in order for a separate thread to read a value. Most languages have support for this in one form or another - for example, in C#, you can flag a variable as volatile in order to assist in this, but explicit synchronization (ie: locking) is typically still required.
Also, if the variable write is not a single CPU instruction (ie: using an interlocked operation or similar), care must be taken to explicitly synchronize the access for read and write - otherwise, you can (on some architectures) get the variable in a third, indeterminate state.
Nothing to add re what happens. Note however that typically there are hardware-level mechanisms to guarantee atomic access to memory at a certain address, of a certain length, in this scenario. For small values, this is more efficient than a user-mode lock like CRITICAL_SECTION
.
Check out .Net framework Interlocked class or the Interlocked* APIs in Win32.