I have a question regarding a race condition scenario. The question:
Consider the following two threads, to be run concurrently in a shared memory (all variables are shared between the two threads).
Thread A
for i = 1 to 5 do
x = x + 1;
Thread B
for j = 1 to 5 do
x = x + 1;
Assuming a single-processor system, that load and store are atomic, that x is initialized to 0, and that x must be loaded into a register before being incremented (and stored back to memory afterwards), what are all the possible values for x after both threads have completed?
Now the answer is 2:10 inclusive. I understand the results of 5:10, but how could x be 2, 3 or 4?
Sequence to get x = 2:
Thread 2 read // Reg_2 = 0
Thread 1 read/write 4 times // x = 4
Thread 2 write // * Reg_2 = 0 --> x = 1
Thread 1 read // Reg_1 = 1
Thread 2 read/write 4 times // x = 5
Thread 1 write // Reg_1 = 1 --> x = 2
Depending on how many write thread 2 does before you preempt at the step marked with *, you will get the result for 3 and 4.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With