Learn

Recall that a program is synchronized when each critical section satisfies the mutual exclusion, progress, and bounded waiting conditions.

Our program from the last exercise failed because multiple threads were allowed to access x at the same time in defiance of the mutual exclusion condition. Remember that condition says that there must only be one thread at a time with access to a critical section.

A common way to fix this issue is with a mutual exclusion lock, or mutex.

To understand this concept, let’s take a look at how we can use a mutex to synchronize our increment-a-number problem.

Previously, our increment() function contained one line, x = x + 1, which was the only critical section in our program. Now, as we can see with the image on the right, we have surrounded our critical section with functions of our mutex object, lock() and unlock().

If a thread calls lock(), it receives the mutex. If thread_one calls lock(), the mutex, mtx, will belong to it. Any other thread that calls lock() on mtx will wait indefinitely until thread 1 releases it by calling unlock().

Think of the critical section as a room only one person is allowed in at a time. A mutex is like the lock on the door. One person enters the room and locks the door behind them while the others wait outside. Once that person leaves, they unlock the door which allows for the next person to enter, and so on.

This pattern of receiving the mutex, incrementing x, and giving up the mutex will repeat until every thread has called increment(), completing the program.

Instructions

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

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?