PreviousNext

Race Conditions

A race condition occurs when two or more threads perform an operation, and the result of the operation depends on unpredictable timing factors; specifically, when each thread executes and waits and when each thread completes the operation.

An example of a race condition is as follows:

1. Both A and B are executing (X = X + 1).

2. A reads the value of X (for example, X = 5).

3. B comes in and reads the value of X and increments it (making X = 6).

4. A gets rescheduled and now increments X. Based on its earlier read operation, A thinks (X+1 = 5+1 = 6). X is now 6. It should be 7 because it was incremented once by A and once by B.

To avoid race conditions, ensure that any variable modified by more than one thread has only one mutex associated with it. Do not assume that a simple add operation can be completed without allowing another thread to execute. Such operations are generally not portable, especially to multiprocessor systems. If it is possible for two threads to share a data point, use a mutex.