A race condition occurs when two or more threads can access shared data and they try to change it at the same time. Because the thread scheduling algorithm can swap between threads at any time, you don't know the order in which the threads will attempt to access the shared data. Therefore, the result of the change in data is dependent on the thread scheduling algorithm, i.e. both threads are "racing" to access/change the data.
A race condition is a situation where-
- The final output produced depends on the execution order of instructions of different processes.
- Several processes compete with each other.
Example: The
following two functions P1 and P2 that share a variable B with an initial value
of 2 execute concurrently-
The
number of distinct values that B can possibly take after the execution is-
Solution-
The different execution orders of the instructions of P1 and P2 produce different results.
Case-01: |
Case-02: |
Case-03: |
Case-04: |
Case-05: |
Case-06: |
1, 2, 3, 4 |
3, 4, 1, 2 |
1, 3, 4, 2 |
1, 3, 2, 4 |
3, 1, 2, 4 |
3, 1, 4, 2 |
C=1 B=2 D=4 B=3 |
D=4 B=3 C=2 B=4 |
C=1 D=4 B=3 B=2 |
C=1 D=4 B=2 B=3 |
D=4 C=1 B=2 B=3 |
D=4 C=1 B=3 B=2 |
- Distinct values that may be produced are 2, 3 and 4.
- Number of distinct values that may be produced = 3
0 Comments