How to prevent race conditions?

First, a race condition occurs when 2 or more threads / process access a shared resource, without synchronization, and one of these modify the resource.

Their modifications maybe interleave, when we expect that modifications should be atomic.

To prevent this, we need to make the access of the shared resource atomic.

This is done using something called Mutual exclusion , where only 1 process can access the resource.

The code sequence that uses mutual exclusion is called critical section.

Only 1 thread at a time execute in the critical section. All other threads have to wait. Once a thread leaves, another can enter.