Multithreading – can multiple threads write the same value to the same variable?
I understand the contention condition and how multiple threads access the same variable. Updates made by an update can be ignored and overwritten by others, but what if each thread writes the same value (not a different value) to the same variable? May even cause problems? This code can:
GlobalVar. property = 11;
(assuming that this property will never be assigned anything except 11), will it cause problems if multiple threads execute it at the same time?
Solution
Problems arise when you read back to that state and do something Writing is a red herring – indeed, as long as this is a word, most environments guarantee that writing will be atomic, but that doesn't mean that the larger code fragment containing this fragment is thread safe First, maybe your global variable contains a different value - otherwise, if you know it's always the same, why is it a variable? Second, maybe you will eventually read this value again?
The question is, it's probably one of the reasons you're writing this shared state - signaling what has happened? This is where it fails: when you don't have a lock structure, there is no implicit memory access order at all It's hard to point out the problem here, because your example does not actually include the use of variables, so here is a simple example of neutral C syntax:
int x = 0,y = 0; //thread A does: x = 1; y = 2; if (y == 2) print(x); //thread B does,at the same time: if (y == 2) print(x);
Thread a will always print 1, but it is fully valid for thread B to print 0 The order of operations in thread a only needs to be observed from the code executed in thread a – thread B can see any combination of states Writes to X and Y may not actually occur in sequence
This happens even on uniprocessor systems, and most people don't want this reordering - your compiler may reorder you On SMP, memory writes can be reordered between the caches of individual processors even if the compiler does not reorder things
If this does not seem to answer for you, please include more details of your example in the question If variables are not used, it is impossible to specify whether this usage is safe or not