Learn

Consider the following example: two people work at a guitar store. One person makes guitars while the other sells them, but both keep track of their inventory number as they create and sell the guitars. Take a look at the pseudocode to the right to see how we could simulate this situation using threads.

We create two threads representing a maker and a seller. When the maker thread calls make_guitar(), the num_guitars variable is incremented. When seller thread calls sell_guitar(), num_guitars is decremented as long as num_guitars is greater than 0.

Both threads must access the shared variable num_guitars which means, in order to synchronize our program, we must enforce mutual exclusion on num_guitars.

Up until now, locking was our only tool to achieve this. Using locks, the seller thread could continuously request a lock on num_guitars, check whether it was greater than one, and then unlock it. This lock, check, unlock cycle is incredibly inefficient.

A more efficient way to handle this is to notify the seller thread when num_guitars is greater than 0. We can do this by using what is called a condition variable.

Let’s walk through sell_guitar(). First, the seller thread locks guitar_mtx so it can check that the value of num_guitars() is greater than 0. While num_guitars == 0 is true, the seller thread waits indefinitely to continue executing until the condition becomes false. It does this by calling the wait() function on the condition variable, guitar_cv, and passing it into guitar_mtx. The wait() function frees the mutex, allowing the maker thread to execute, and then waits for the signal to continue.

On the maker thread side, each time it calls make_guitar(), num_guitars is increased by 1, and the condition variable is notified. The notification alerts the seller thread, which then locks the mutex again and continues on with execution.

The biggest advantage here is that the seller thread is not constantly requesting the mutex to check whether num_guitars is greater than 0. It simply waits to be notified, then retrieves the mutex.

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?