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.