Locks: The Basic Idea

This lesson presents the basic idea and motivation behind locks.

We'll cover the following...

As an example, assume some critical section looks like this, the canonical update of a shared variable:

Press + to interact
balance = balance + 1;

Of course, other critical sections are possible, such as adding an element to a linked list or other more complex updates to shared structures but let’s just keep to this simple example for now. To use a lock, you add some code around the critical section like this:

Press + to interact
lock_t mutex; // some globally-allocated lock ’mutex’
...
lock(&mutex);
balance = balance + 1;
unlock(&mutex);

A lock is just a variable, and thus to use one, you must declare a lock variable of some kind (such as mutex above). This lock variable (or just ...