deadlock

Threads that can run at once take locks in orders that form a cycle.

Group
Code
Runs
On by default
Level
warning
Reads
Every file
Fix
None: which order to take the locks in is a design choice

Why

One thread takes a lock and then another while a thread that can run at the same time takes them in the opposite order, or the locks of several threads form a longer cycle. Each thread can take its first lock and then wait forever for the next, which another holds. A lock taken again while the same thread holds it waits for itself unless the lock is recursive. Take every set of locks in one order everywhere, or hold one lock at a time. Ur reads locks by the expression that names them, so each finding lists that assumption.

The fix, as Ur suggests it: take the locks in one order everywhere.

For agents

Take locks in one fixed order everywhere, and never take a lock the same thread already holds.

Example

src/transfer.c
#include <pthread.h>

static pthread_mutex_t accounts, ledger;
static long balance, entries;

static void *pay(void *arg) {
    pthread_mutex_lock(&accounts);
    pthread_mutex_lock(&ledger);
    balance -= 10;
    entries++;
    pthread_mutex_unlock(&ledger);
    pthread_mutex_unlock(&accounts);
    return NULL;
}

static void *audit(void *arg) {
    pthread_mutex_lock(&ledger);
    pthread_mutex_lock(&accounts);
    entries = balance;
    pthread_mutex_unlock(&accounts);
    pthread_mutex_unlock(&ledger);
    return NULL;
}

int main(void) {
    pthread_t p, a;
    pthread_create(&p, NULL, pay, NULL);
    pthread_create(&a, NULL, audit, NULL);
    pthread_join(p, NULL);
    pthread_join(a, NULL);
    return 0;
}
What Ur prints
$ ur lint --rule deadlock
warning[deadlock]: `ledger` is taken while `accounts` is held, and the thread running `audit` takes them in the opposite order, so each can wait for the other
  --> ./src/transfer.c:8:5 function `pay`
  = step 1: ./src/transfer.c:8:5 the thread running `pay` takes `ledger` while holding `accounts`
  = step 2: ./src/transfer.c:18:5 the thread running `audit` takes `accounts` while holding `ledger`
  = step 3: ./src/transfer.c:27:5 a thread running `pay` starts here
  = step 4: ./src/transfer.c:28:5 a thread running `audit` starts here
  = assumes: locks-by-name
  = hint: take the locks in one order everywhere
  = see: System Deadlocks, E. G. Coffman, M. J. Elphick, and A. Shoshani, ACM Computing Surveys 3(2) (1971-06-01), https://doi.org/10.1145/356586.356588
0 clone classes and 1 concurrency finding in 1 file

Try it in the playground →

Source

System Deadlocks, E. G. Coffman, M. J. Elphick, and A. Shoshani, ACM Computing Surveys 3(2) (1971-06-01).