educative.io

Why get a non-zero value on Thread Unsafe Class?

I understand that Counter Program example. But I am confused here. I know during the thread 1 and thread 2 running, the result won’t always be 0. But after both thread 1 and thread 2 finish their loop, in the end the outcome should be 0. Did I miss anything?

1 Like

Hi Franklin,

Thank you for reaching out!

We are looking into this question and will soon get back to you.

Regards,
Team Educative

Hi @Franklin,
Thanks for reaching out. I can clarify this with an example. Suppose

  1. thread1 is currently scheduled on the CPU and enters the function. It performs step A i.e. reads the value of the count from the register, which is 0.
  2. The operating system then decides to context switch thread1 and bring in thread2 .
  3. thread2 gets scheduled and luckily gets to complete all the three steps A , B and C for all iterations of the for loop. So the value is now -100. Now it gets switched out for thread1 .
  4. thread1 comes back and since its state was saved by the operating system, it still has the stale value of 0 that it read before being context switched. It doesn’t know that behind its back the value of the variable has been updated. It, unfortunately, thinks the value is still 0, adds 100 to it and overwrites the existing -100 with its own computed 100.

If the threads executed serially, however, the final value would have been 0.

Hope this helps! Let us know if you have any other questions :slight_smile:

Regards,
Ayesha Alvi | Developer Advocate