Back to course home
0% completed
Vote For New Content
Race Condition while updating ``isSame`` variable with LOGICAL (&) operator
Mahendra Reddy
Apr 7, 2024
When multiple threads are updating ***isSame*** variable
isSame &= isSameTreeMultiThreaded(p.left, q.left, numThreads/2); SIMILAR TO isSame = isSame & isSameTreeMultiThreaded(p.left, q.left, numThreads/2);
- It reads isSame which is thread safe gives latest value due to primitive
- & operator with isSame variable ( one more, by the time it evaluates through recursive function, isSame variable could be outdated )
- Updating isSame variable which is thread safe due to primitive
But, All the above 3 steps together is not atomic.
Consider the scenario:
isSame is true by default,
- Thread-1 reads as true
- Thread-2 reads as true
- Thread-1 receives false from recursive function and updates it with false
- Thread-2 receive true from recursive function and update it with true because it had already read isSame to be true
So, finally, we have true is saved in isSame variable which is wrong.
Volatile (Use cases):
- Date races caused by shuffling of instructions by JAVA optimization based on happens-before relation. Volatile keyword, make sure all instructions before volatile variable is executed before it.
- Partial reading of double, long which are 64-bit because update of 64-bit is a 2-step process.
My Solution: We should synchronize the update of isSame variable. With understanding, I did not see any use of volatile keyword here.
Note: My understanding could be partial, Since these programs were written by experts, there might be some rational behind it. I would like to know about it.
Hoping of quick reply.
Thank You,
Mahendra Reddy
3
0
Comments
Comments
On this page