Race Condition: A race condition is realized when more than one thread tries to write to the same variablesimultaneously. Since we don't know which thread will access the variable first, we can't safely predict what will happen. All threads will try to access it first; they will race to access the variable.
Let's try to understand it using the below example:
The race condition occurs because these threads can execute the following steps concurrently:
Read the current value of 'i'.
Increment the value of 'i' by '1'.
Write the updated value back to 'i'.
Since multiple threads are executing these steps simultaneously, it is unpredictable that which thread will complete these steps first. As a result, the value of 'i' will not be updated correctly, and we will observe inconsistencies or unexpected results. This unpredictability is the essence of a race condition.
Race conditions are avoided by using mutexes, which ensure exclusive access to shared resources among multiple threads.