Q163: Concurrent Threads Contd.

This question is in continuation of Question 44.

Answer the question below based on the following code:


Global Variable:

int count = 0;

Thread1:

for(int i = 1; i < 50000; i++)

count++;

Thread2:

for(int i = 1; i < 20000; i++)

count++;

 

Question #163: What can be said about the value of count?

Option:

  1. Value of count will always be less than or equal to 70000.
  2. Value of count will always be equal to 70000.
  3. Value of count will always be greater than or equal to 70000.
  4. Nothing can be said about value of count.

Solution: The correct answer is the first one. When there is no interleaving, value might be equal to 70000. When there is interleaving, value can only be less than 70000, and not greater.

Q44: Concurrent Threads

Answer the question below based on the following code:


Global Variable:

int count = 0;

Thread1:

for(int i = 1; i < 50000; i++)

count++;

Thread2:

for(int i = 1; i < 20000; i++)

count++;

 

Question #44: Given that the two threads run concurrently, what will be the value of count at the end of execution of the two threads?

Options:

  • Value of count will be 70000.
  • Value of count can’t be predicted.
  • There is a race condition in the above program.
  • Both B and C.

Solution: count++ is not an atomic statement and is broken down into many instructions while executing. Following is an illustration of how things can go wrong:

Thread 1 Thread 2   Integer value
0
read value 0
read value 0
increase value 0
increase value 0
write back 1
write back 1

Hence, 4th option is the correct solution.