Learn

Recall the increment-a-number problem. In the no-locks solution, the race condition arose because the `x = x + 1` operation actually takes place in three atomic steps. If two threads try to complete those steps at the same time, the value of `x` will not be set properly.

The solution from exercise three was to use locks to ensure that only one thread at a time had access to `x`. But there is another solution which is far simpler: make `x` an atomic variable.

An atomic variable is a variable that can be modified in an inherently thread-safe manner without the use of locks or any other synchronization mechanism. The variable is atomic because the operations required to modify it take place, from our threads’ perspective, in exactly one atomic step.

So, if we simply declare `x` with type `atomic_int`, we can forgo using locks to synchronize our program. Because each `x = x + 1` operation will take place in one atomic step, by definition, it cannot take place concurrently with any other atomic step. So, we are at no risk of a race condition.

### Instructions

Click Next when you’re ready to move on to the next exercise.