user2905368
user2905368

Reputation: 3

Concurrent addition and subtraction

What happens when two threads try to modify the same property at the exact same time? For instance, if I have an int value = 0 and I have thread A value += 5 and thread B value -= 3, what happens? I should get the same result no matter which order the threads access the variable in, but I imagine they can access that variable at the EXACT same time.

Upvotes: 0

Views: 737

Answers (2)

Zac Wrangler
Zac Wrangler

Reputation: 1445

No, you won't get the same result. Even though the operation is simple, it is not an atomic operation w.r.t the processor. Simply speaking, the processor needs to fetch the value from the memory to its register, conduct arithmetic instructions and store the value back to the memory. Therefore, they may get the same value of 0 and the value stored back depends on which is the last.

The result you may get will vary from different runs, it could be 5, -3, 2

Upvotes: 1

shazin
shazin

Reputation: 21883

There is no exact same time in Computer. It is one nano second or less for one thread and then for the other. It is called time slicing. For us += and -= might be single operations but for the Processor those are multiple instructions.

The above code without synchronization will cause in race condition and will not guarantee same value all the time.

Upvotes: 1

Related Questions