1lock(&m);2if (info != NULL)3 fputs(info, out);4unlock(&m);info"msg"1lock(&m);2info = NULL;3unlock(&m);1while True:2 for k, _ in sel.select():3 k.data(k.fileobj)CPUmsgNULLprintclearfileprintdonedatastate
Left: two threads, the shared pointer info and the lock mRight: the inbox of events, the disk and the event loopTokens: the CPU, values read and written, the lock's key, events and the saved stateLeft: two threads in C share one pointer, info, and one lock, m. The CPU puck shows which line runs. A switch between Thread 1's check and its use lets Thread 2 set info to NULL, and Thread 1 crashes; with the lock, Thread 2 waits for the key. Right: an event loop runs one handler at a time; a blocking read freezes it, and an asynchronous read finishes later from saved state. The figure has one CPU. With several CPUs, two threads can run truly at the same time, so the race needs no timer interrupt at all, and event handlers spread over cores need locks again.

A race

  1. Two threads share one pointer, info, which points at the text msg. Thread 1 prints it if it is not NULL. Thread 2 sets it to NULL. Each line is correct on its own. Ignore the faint lock lines for now.

Fixing it

Events

What happens

;; step 1/11 · two-threads
shared     info  -> "msg"     (a pointer to some text)
thread 1   if (info != NULL)        check
               fputs(info, out);    use
thread 2   info = NULL;             clear

a race: two threads use one memory location,
and at least one of them writes it (MIT 6.1810)

from MySQL (OSTEP fig. 32.2): thd->proc_info

The two threads are the MySQL bug from OSTEP chapter 32, with thd->proc_info shortened to info. lock() and unlock() on the cards are one-line wrappers around pthread_mutex_lock() and pthread_mutex_unlock(), so the lines stay short. The figure has one CPU. With several CPUs, two threads can run truly at the same time, so the race needs no timer interrupt at all, and event handlers spread over cores need locks again.