Search code examples
multithreadingpreemption

basic multithreading


I have the following Interview question:

class someClass
{
    int sum=0;
    public void foo()
    {
        for(int i=0; i<100; i++)
        {
            sum++
        }
    }
}

There are two parallel threads running through the foo method. the value of sum at the end will vary from 100 to 200. the question is why. As I understand only one thread gets a cpu and threads get preempted while running. At what point can the disturbance cause the sum not reaching 200?


Solution

  • The line sum++ is a race condition.

    Both threads can read the value of sum as say 0, then each increments its value to 1 and stores that value back. This means that the value of sum will be 1 instead of 2.

    Continue like that and you will get a result between 100 and 200.