Operating Systems Module 4: Concurrency Lesson 4.2 14 min

Locks and atomic instructions

A lock makes a critical section one-at-a-time. It is built from atomic hardware instructions, test-and-set and compare-and-swap, because a lock made of ordinary steps has the same race as the counter.

You know what has to happen: only one thread may be inside the critical section at a time. The obvious tool is a lock (also called a mutex, short for mutual exclusion). A thread takes the lock before the critical section and releases it after. If the lock is already taken, the thread waits.

That sounds easy. But think about how the lock itself would be written. A lock is a variable, and checking and changing a variable is, again, a few instructions. Is the lock safe from the very race it is meant to prevent?

A lock around the counter

First, what a working lock does. This is the race from Lesson 4.1 with mutex on: every increment is wrapped in lock m and unlock m, and the schedule is the same unlucky one, A B A B A B.

The same schedule, with a lock

  1. Start: count is 0 The shared variable count holds 0. 2 threads each run count = count + 1. The compiler turns that one line into three instructions, wrapped in a lock and an unlock, and the CPU can switch threads between any two of them.
    count (shared)
    0
    A: r
    –
    B: r
    –
    Lock m
    free
    Updates lost
    0
  2. A takes the lock A runs lock m and gets it, because nobody holds it. From here until unlock, no other thread can get past lock m.
    count (shared)
    0
    A: r
    –
    B: r
    –
    Lock m
    held by A
    Updates lost
    0
  3. B blocks on the lock B runs lock m, but A holds it. The kernel puts B to sleep on the lock and it takes no more turns until the lock is handed over.
    count (shared)
    0
    A: r
    –
    B: r
    –
    Lock m
    held by A
    Updates lost
    0
  4. A loads count A copies count into its own register: r = 0. count itself has not changed, and the copy is private to A.
    count (shared)
    0
    A: r
    0
    B: r
    –
    Lock m
    held by A
    Updates lost
    0
  5. B is blocked B was picked, but it is waiting for lock m, which A holds. A blocked thread cannot run, so nothing happens in this step. The lock holder has to carry on first. The schedule picked B again, but a blocked thread cannot run. The step is wasted and A carries on.
    count (shared)
    0
    A: r
    0
    B: r
    –
    Lock m
    held by A
    Updates lost
    0
  6. A adds 1 A adds 1 to its register: r = 1. This happens only in A's register. count has not been touched.
    count (shared)
    0
    A: r
    1
    B: r
    –
    Lock m
    held by A
    Updates lost
    0
  7. B is blocked B was picked, but it is waiting for lock m, which A holds. A blocked thread cannot run, so nothing happens in this step. The lock holder has to carry on first.
    count (shared)
    0
    A: r
    1
    B: r
    –
    Lock m
    held by A
    Updates lost
    0
  8. A stores count A writes r = 1 back into count. Nobody changed count since A loaded it, so this update is kept.
    count (shared)
    1
    A: r
    1
    B: r
    –
    Lock m
    held by A
    Updates lost
    0
  9. A unlocks, and B gets the lock A runs unlock m. B was waiting, so the lock goes straight to it and it can carry on.
    count (shared)
    1
    A: r
    1
    B: r
    –
    Lock m
    held by B
    Updates lost
    0
  10. B loads count B copies count into its own register: r = 1. count itself has not changed, and the copy is private to B.
    count (shared)
    1
    A: r
    1
    B: r
    1
    Lock m
    held by B
    Updates lost
    0
  11. B adds 1 B adds 1 to its register: r = 2. This happens only in B's register. count has not been touched.
    count (shared)
    1
    A: r
    1
    B: r
    2
    Lock m
    held by B
    Updates lost
    0
  12. B stores count B writes r = 2 back into count. Nobody changed count since B loaded it, so this update is kept.
    count (shared)
    2
    A: r
    1
    B: r
    2
    Lock m
    held by B
    Updates lost
    0
  13. B unlocks B runs unlock m. Nobody is waiting, so the lock is free again.
    count (shared)
    2
    A: r
    1
    B: r
    2
    Lock m
    free
    Updates lost
    0
  14. Finished: count is 2 Every thread finished and count is 2, which is what 2 increments should give. Nothing was lost: the lock let one thread at a time through the three instructions.
    count (shared)
    2
    A: r
    1
    B: r
    2
    Lock m
    free
    Updates lost
    0

The scheduler tried to give B turns, and the lock made B wait. A ran the three instructions in one piece, then unlocked, and the lock went straight to B. The count is 2 whatever order you pick: with the lock on, the schedule can change when things happen, but not the answer. Press Try it and type any schedule you like.

How do you build a lock?

Here is the obvious way. The lock is a variable, 0 for free and 1 for taken. To lock, read it, and if it is 0, set it to 1. To unlock, set it to 0.

r = lock                 (read it)
if (r != 0) goto again   (taken: try again)
lock = 1                 (free: take it)
...critical section...
lock = 0

Run it with the unlucky schedule. Watch what each thread has learned when it sets the lock.

A lock built from ordinary steps

  1. Start Two threads want the same lock. Each one runs the code below: it reads the lock, and if it looks free, sets it and goes into the critical section. lock is 0 (free) and count is 0.
    lock
    0
    count
    0
    A: r
    –
    B: r
    –
    In critical section
    0
    Spins
    0
  2. A reads the lock A copies lock into r and gets 0. It looks free. But this is only a copy: nothing stops another thread from changing lock before A acts on it.
    lock
    0
    count
    0
    A: r
    0
    B: r
    –
    In critical section
    0
    Spins
    0
  3. B reads the lock B copies lock into r and gets 0. It looks free. But this is only a copy: nothing stops another thread from changing lock before B acts on it.
    lock
    0
    count
    0
    A: r
    0
    B: r
    0
    In critical section
    0
    Spins
    0
  4. A decides the lock is free r is 0, so A will take the lock. It has not set it yet: this decision is based on a value that may already be stale.
    lock
    0
    count
    0
    A: r
    0
    B: r
    0
    In critical section
    0
    Spins
    0
  5. B decides the lock is free r is 0, so B will take the lock. It has not set it yet: this decision is based on a value that may already be stale.
    lock
    0
    count
    0
    A: r
    0
    B: r
    0
    In critical section
    0
    Spins
    0
  6. A sets the lock A sets lock = 1 and enters the critical section.
    lock
    1
    count
    0
    A: r
    0
    B: r
    0
    In critical section
    1
    Spins
    0
  7. B sets the lock and walks in too B sets lock = 1, exactly as A did. Both of them read 0 before either wrote 1, so both think they own the lock. Two threads are now inside the critical section: mutual exclusion is broken.
    lock
    1
    count
    0
    A: r
    0
    B: r
    0
    In critical section
    2 (broken!)
    Spins
    0
  8. A runs the critical section A does the protected work: count = count + 1. B is in here as well. The lock has failed.
    lock
    1
    count
    1
    A: r
    0
    B: r
    0
    In critical section
    2 (broken!)
    Spins
    0
  9. A releases the lock A sets lock = 0 and leaves.
    lock
    0
    count
    1
    A: r
    0
    B: r
    0
    In critical section
    1
    Spins
    0
  10. B runs the critical section B does the protected work: count = count + 1.
    lock
    0
    count
    2
    A: r
    0
    B: r
    0
    In critical section
    1
    Spins
    0
  11. B releases the lock B sets lock = 0 and leaves.
    lock
    0
    count
    2
    A: r
    0
    B: r
    0
    In critical section
    0
    Spins
    0
  12. Finished, but the lock failed Two threads were inside the critical section at the same moment, so the "lock" did not protect anything. Reading the lock and setting it were two separate instructions, and a switch between them is enough.
    lock
    0
    count
    2
    A: r
    0
    B: r
    0
    In critical section
    0
    Spins
    0

The lock failed in exactly the way the counter did: checking the lock and setting it are two steps, and another thread slipped in between them. Locking cannot be built from ordinary reads and writes alone. It needs an instruction that does the check and the change in one indivisible step.

Atomic instructions

An instruction is atomic when nothing can happen in the middle of it: no other thread, and no interrupt, can see it half done. Every modern CPU has some. Two are classics.

Test-and-set (tas) does two things at once: it sets the variable to 1 and gives you back the old value. If the old value was 0, you got the lock. If it was 1, someone else had it, and your write changed nothing.

A spin lock with test-and-set

  1. Start Two threads want the same lock. Each one uses one atomic instruction, test-and-set, to try to take it. lock is 0 (free) and count is 0.
    lock
    0
    count
    0
    A: r
    –
    B: r
    –
    In critical section
    0
    Spins
    0
  2. A runs test-and-set In one indivisible step, the hardware reads the old lock value (0) into r and sets lock to 1. The lock was free, and now A owns it. No other thread can get in between the read and the write: that is what atomic means.
    lock
    1
    count
    0
    A: r
    0
    B: r
    –
    In critical section
    0
    Spins
    0
  3. B runs test-and-set In one indivisible step, the hardware reads the old lock value (1) into r and sets lock to 1. It was already 1, so the lock stays held, and B learns that somebody else owns it.
    lock
    1
    count
    0
    A: r
    0
    B: r
    1
    In critical section
    0
    Spins
    0
  4. A knows it has the lock r is 0, so the lock was free when A took it. On to the critical section.
    lock
    1
    count
    0
    A: r
    0
    B: r
    1
    In critical section
    1
    Spins
    0
  5. B spins r is 1, so B did not get the lock. It goes straight back to test-and-set. This is a spin lock: the thread keeps using the CPU while it waits. B keeps trying: it goes round the loop again. A thread that loops like this is spinning.
    lock
    1
    count
    0
    A: r
    0
    B: r
    1
    In critical section
    1
    Spins
    1
  6. A runs the critical section A does the protected work: count = count + 1. Nobody else can be in here: every other thread would have got back r = 1.
    lock
    1
    count
    1
    A: r
    0
    B: r
    1
    In critical section
    1
    Spins
    1
  7. A releases the lock A sets lock = 0. The next test-and-set by a spinning thread will get back 0 and win it.
    lock
    0
    count
    1
    A: r
    0
    B: r
    1
    In critical section
    0
    Spins
    1
  8. B runs test-and-set In one indivisible step, the hardware reads the old lock value (0) into r and sets lock to 1. The lock was free, and now B owns it. No other thread can get in between the read and the write: that is what atomic means.
    lock
    1
    count
    1
    A: r
    0
    B: r
    0
    In critical section
    0
    Spins
    1
  9. B knows it has the lock r is 0, so the lock was free when B took it. On to the critical section.
    lock
    1
    count
    1
    A: r
    0
    B: r
    0
    In critical section
    1
    Spins
    1
  10. B runs the critical section B does the protected work: count = count + 1. Nobody else can be in here: every other thread would have got back r = 1.
    lock
    1
    count
    2
    A: r
    0
    B: r
    0
    In critical section
    1
    Spins
    1
  11. B releases the lock B sets lock = 0. The next test-and-set by a spinning thread will get back 0 and win it.
    lock
    0
    count
    2
    A: r
    0
    B: r
    0
    In critical section
    0
    Spins
    1
  12. Finished: count is 2 The threads went through the critical section one at a time, and count is 2. The spinning thread burned CPU while it waited (1 wasted round).
    lock
    0
    count
    2
    A: r
    0
    B: r
    0
    In critical section
    0
    Spins
    1

B never got into the critical section while A was inside. Instead it spun: it went round the loop, running test-and-set again and again, until A unlocked. That is a spin lock. It is simple and fast when the wait is short, but a spinning thread uses the CPU while it waits and gets nothing done.

Compare-and-swap (cas) is the other classic. cas(count, old, new) says: “if count is still equal to old, set it to new, and tell me whether you did”. With it you do not need a lock at all for a counter. Read the value, work out the new one, and swap it in only if nobody changed it. If somebody did, try again.

Compare-and-swap: retry instead of lock

  1. Start Two threads each want to add 1 to count, with no lock. They use compare-and-swap (cas) to make sure count did not change under them. count is 0.
    count
    0
    A: old
    –
    B: old
    –
    Retries
    0
  2. A reads count A copies count into old: old = 0. No lock is taken.
    count
    0
    A: old
    0
    B: old
    –
    Retries
    0
  3. B reads count B copies count into old: old = 0. No lock is taken.
    count
    0
    A: old
    0
    B: old
    0
    Retries
    0
  4. A works out the new value A computes new = old + 1 = 1, privately.
    count
    0
    A: old
    0
    B: old
    0
    Retries
    0
  5. B works out the new value B computes new = old + 1 = 1, privately.
    count
    0
    A: old
    0
    B: old
    0
    Retries
    0
  6. A's compare-and-swap succeeds cas checks, in one indivisible step, that count still equals old (0). It does, so it stores new (1) and reports success. Nobody changed count since A read it.
    count
    1
    A: old
    0
    B: old
    0
    Retries
    0
  7. A is done A's increment is in. It never held a lock, so nobody ever had to wait for it.
    count
    1
    A: old
    0
    B: old
    0
    Retries
    0
  8. B's compare-and-swap fails cas checks that count still equals old (0), but count is now 1. Somebody else got there first, so cas changes nothing and reports failure. No update is lost: B just has to start over.
    count
    1
    A: old
    0
    B: old
    0
    Retries
    0
  9. B retries B goes back and reads count again, so that old is up to date (1), then tries the compare-and-swap once more.
    count
    1
    A: old
    0
    B: old
    –
    Retries
    1
  10. B reads count B copies count into old: old = 1. No lock is taken.
    count
    1
    A: old
    0
    B: old
    1
    Retries
    1
  11. B works out the new value B computes new = old + 1 = 2, privately.
    count
    1
    A: old
    0
    B: old
    1
    Retries
    1
  12. B's compare-and-swap succeeds cas checks, in one indivisible step, that count still equals old (1). It does, so it stores new (2) and reports success. Nobody changed count since B read it.
    count
    2
    A: old
    0
    B: old
    1
    Retries
    1
  13. B is done B's increment is in. It never held a lock, so nobody ever had to wait for it.
    count
    2
    A: old
    0
    B: old
    1
    Retries
    1
  14. Finished: count is 2 Both increments are in: count is 2. One thread had to retry, and nobody held a lock.
    count
    2
    A: old
    0
    B: old
    1
    Retries
    1

No update was lost and no lock was held: B noticed it had been beaten, and tried again. This lock-free style is used inside many data structures. It is harder to get right than a lock for anything more than a counter, though.

Spin or sleep?

A thread that cannot get a lock has two choices. It can spin, burning CPU and hoping the lock frees up very soon. Or it can sleep: ask the kernel to take it off the CPU until the lock is released. Sleeping costs a system call and a context switch (Lesson 2.5), but a sleeping thread uses no CPU. Spinning is better when the lock is held for a very short time, and on a machine with several cores. Sleeping is better when the wait may be long. On a single core, spinning is almost pointless: the thread that holds the lock cannot run while the spinner has the CPU.

Locks in C

POSIX threads give you a mutex. pthread_mutex_lock takes it, sleeping if it is held, and pthread_mutex_unlock releases it. This is the million-increment program from last lesson with one change: the increment is inside the lock.

mutex.c
#include <pthread.h>
#include <stdio.h>

long counter = 0;
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;

void *work(void *arg) {
    (void)arg;
    for (int i = 0; i < 1000000; i++) {
        pthread_mutex_lock(&m);         /* one thread at a time past here */
        counter++;
        pthread_mutex_unlock(&m);
    }
    return NULL;
}

int main(void) {
    pthread_t a, b;
    pthread_create(&a, NULL, work, NULL);
    pthread_create(&b, NULL, work, NULL);
    pthread_join(a, NULL);
    pthread_join(b, NULL);
    printf("counter = %ld\n", counter);
    return 0;
}

Output (one run)

counter = 2000000

Exactly 2000000, every time. The price is speed: each increment now takes and releases a lock, and when both threads fight over it, one of them waits. A lock makes code correct, not fast. Keep critical sections as short as you can.

In the real world

Linux builds its user-space locks on the futex (fast user-space mutex). Locking a free futex is a single atomic instruction in your own program, with no system call at all. Only when the lock is already held does the thread call into the kernel to sleep, and only when someone is waiting does an unlock call the kernel to wake it. So an uncontended lock costs almost nothing, and a contended one sleeps instead of spinning. The same idea is used in the standard mutex of most languages, and many of them spin for a very short while first, hoping the holder is nearly done.

The kernel itself uses spin locks for very short critical sections (it cannot sleep while handling an interrupt) and sleeping locks for long ones.

Quick check

Quick check

  1. Why does `if (!locked) locked = 1;` fail as a lock?
  2. What does test-and-set return?
  3. What does compare-and-swap do?
  4. When is a spin lock a bad idea?

Recap

  • A lock (mutex) makes a critical section one-at-a-time. With it, the counter is always right.
  • A lock made of ordinary reads and writes has the same race as the counter. Locks need atomic instructions.
  • Test-and-set sets a variable and returns its old value in one step. Compare-and-swap writes only if the value is still what you expected.
  • A thread waiting for a lock can spin (burn CPU) or sleep (ask the kernel). Linux futexes do the fast case in user space and sleep in the kernel only when needed.

Next: a lock lets one thread in. What if three threads may share two printers, or one thread must wait for another to produce something?

Your progress is saved in this browser. Sign in to keep it on every device. Free, no password.

Join the discussion