Reputation: 419
I have a question: Consider a x32 System, therefore for a uint32_t variable does the system read and write to it atomically? Meaning, that the entire operation of read or write can be completed in one instruction cycle. If this is the case then for a multi-threaded x32 system we wont have to use locks for just reading or writing into a uint32_t variable. Please confirm my understanding.
Upvotes: 0
Views: 138
Reputation: 4713
The issue is that variables aren't updated instantly.
Each processor's core has its own private memory (L1 and L2 caches). So if you modify a variable, say x++
, in two different threads on two different cores - then each core updates their own version of x
.
Atomic operations and mutexes ensure synchronization of these variables with the shared memory (RAM / L3 cache).
Upvotes: 0
Reputation: 133978
Yes, one needs to use locks or some other appropriate mechanism, like the atomics.
- Two expression evaluations conflict if one of them modifies a memory location and the other one reads or modifies the same memory location.
- The execution of a program contains a data race if it contains two conflicting actions in different threads, at least one of which is not atomic, and neither happens before the other. Any such data race results in undefined behavior.
Additionally if you've got a variable that is not volatile-qualified then the C standard does not even require that the changes hit to the memory at all; unless you use some synchronization mechanism the data races could have much longer spans in an optimized program than one would perhaps initially think could be possible - for example the writes can be totally out of order and so forth.
Upvotes: 3
Reputation: 214255
It is only atomic if you write the code in assembler and pick the appropriate instruction. When using a higher level language, you don't have any control over which instructions that will get picked.
If you have some C code like a = b;
then the machine code generated might be "load b into register x", "store register x in the memory location of a", which is more than one instruction. An interrupt or another thread executed between those two will mean data corruption if it uses the same variable. Suppose the other thread writes a different value to a
- then that change will be lost when returning to the original thread.
Therefore you must use some manner of protection mechanism, such as _Atomic
qualifier, mutex or critical sections.
Upvotes: 3
Reputation: 11178
The usage of locks is not (only) to ensure atomicity, 32-bit variables are already been written atomically.
Your problem is to protect simultaneous writing:
int x = 0;
Function 1: x++;
Function 2: x++;
If there is no synchronization, x might up end as 1 instead of 2 because function 2 might be reading x = 0
, before function 1 modifies x. The worst thing in all this is that it might happen or not at random (or at your client's PC), so debugging is difficult.
Upvotes: 2