Lecture: locking

Preparation

Multi-threaded hash table

Locks

Dead locks

Lock implementation

struct lock { int locked; };

void acquire(struct lock *l)
{
  for (;;) {
    if (l->locked == 0) { // A: test
      l->locked = 1;      // B: set
      return;
    }
  }
}

void release(struct lock *l)
{
  l->locked = 0;
}
struct lock { _Atomic int locked; };

void acquire(struct lock *l)
{
  for (;;) {
    if (atomic_exchange(&l->locked, 1) == 0)
      return;
  }
}