Mutexes and monitors

Please work out the pre-lab problems before your next lab section. The GSI/IAs will go over all problems during the lab section.

[in-lab] 1. Acquiring and releasing mutexes with RAII

RAII (Resource Acquisition Is Initialization) is a programming idiom that is commonly used to acquire/release mutexes in concurrent programs. The basic idea is to create a class (often called a lock guard) whose constructor acquires the mutex and whose destructor releases the mutex. The program can then define the lock guard as a local variable when it needs to acquire the lock, then let the compiler automatically call the destructor (and release the lock) whenever that local variable leaves scope. This idiom makes it easy to release the mutex, regardless of how the program leaves the scope (e.g., return statement, exception). You will find this idiom handy when you write Project 2 and 4.

A. Modify the following program (from the Project 1 handout) to use RAII. Remember that you can create a new scope anywhere in your program, even if it doesn't correspond nicely to a function, if-statement, or loop.

#include <iostream>
#include "thread.h"

using std::cout;
using std::endl;

mutex mutex1;
cv cv1;

int child_done = 0;             // global variable; shared between the two threads

void child(void *a)
{
    char *message = (char *) a;
    mutex1.lock();
    cout << "child called with message " << message << ", setting child_done = 1" << endl;
    child_done = 1;
    cv1.signal();
    mutex1.unlock();
}

void parent(void *a)
{
    intptr_t arg = (intptr_t) a;
    mutex1.lock();
    cout << "parent called with arg " << arg << endl;
    mutex1.unlock();

    thread t1 ((thread_startfunc_t) child, (void *) "test message");

    mutex1.lock();
    while (!child_done) {
        cout << "parent waiting for child to run\n";
        cv1.wait(mutex1);
    }
    cout << "parent finishing" << endl;
    mutex1.unlock();
}

int main()
{
    cpu::boot((thread_startfunc_t) parent, (void *) 100, 0);
}

B. Think about what resources are acquired and released in Project 2, and consider using RAII to acquire/release these resources.

[pre-lab] 2. Monitors

Solve question 5 from the Fall 2016 midterm.