Concurrency bugs and event-based concurrency
لم يُترجم بعد؛ يُعرض باللغة الإنجليزية
عن هذا الدرس
Most concurrency bugs in real software are not deadlocks. They are two simpler patterns: a check and a use split apart by a thread switch, or two steps that run in the wrong order. Watch a real bug from MySQL crash when the scheduler switches threads at the worst moment, fix it with one lock, then meet the other way to handle many jobs at once: an event loop that runs one handler at a time and needs no locks, as long as nothing blocks. The Locks, Condition variables and The four conditions for deadlock lessons are good warm-ups.
Two threads, one pointer
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.
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اقرأ الدرس خطوة بخطوة
Two threads, one pointer
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.
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_infoThread 1 checks
The scheduler runs Thread 1 on the CPU. It checks info != NULL. info points at msg, so the check passes, and Thread 1 moves on to its fputs line.
CPU runs thread 1 line if (info != NULL) read info -> "msg" result true: go on to fputsA switch at the worst moment
Before fputs runs, a timer interrupt fires and the scheduler switches the CPU to Thread 2. Thread 2 sets info to NULL. Thread 1 is paused between its check and its use, so it cannot notice.
timer interrupt -> scheduler switch thread 1 paused after its check thread 2 runs write info = NULL thread 1 still "knows" its check was trueThread 1 crashes
Thread 1 resumes at fputs. Its check said yes, but info is now NULL, so fputs reads through a NULL pointer and the program crashes. This is an atomicity violation: the check and the use were meant to happen as one.
switch back to thread 1, at fputs read info -> NULL fputs dereferences NULL: crash (undefined behaviour; on Linux usually SIGSEGV) atomicity violation (Lu et al.): a code region meant to be atomic, but the atomicity is not enforced the race as a Python simulation: import sys def thread1(): if info is not None: # check yield # a timer interrupt can switch here sys.stdout.write(info) # use, like fputs def thread2(): global info info = None # info = NULL yield def run(order): # which thread runs at each turn global info info = "msg\n" threads = {1: thread1(), 2: thread2()} try: for t in order: next(threads[t], None) except TypeError: print("crash: info was None") run([1, 1, 2]) # thread 1 finishes first run([1, 2, 1]) # switch between check and use prints: msg crash: info was NoneFix: one lock around both
Run it again with one lock, m, around both. Thread 1 takes m, then the switch comes. Thread 2's lock(&m) waits until Thread 1 unlocks. The check and the use now run together, and Thread 2 clears info afterwards.
thread 1 lock(&m) holds m switch thread 2: lock(&m) m is taken: it blocks switch thread 1: check true, prints msg unlock(&m) m is free thread 2 gets m, info = NULL, unlock(&m) pthread_mutex_lock(3p): if the mutex is locked by another thread, the caller blocks until it is free the whole program (C99, POSIX threads): #define _POSIX_C_SOURCE 200809L #include <pthread.h> #include <stdio.h> static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER; static const char *info = "msg\n"; static FILE *out; static void lock(pthread_mutex_t *l) { pthread_mutex_lock(l); } static void unlock(pthread_mutex_t *l) { pthread_mutex_unlock(l); } static void *thread1(void *arg) { (void)arg; lock(&m); if (info != NULL) fputs(info, out); unlock(&m); return NULL; } static void *thread2(void *arg) { (void)arg; lock(&m); info = NULL; unlock(&m); return NULL; } int main(void) { pthread_t a, b; out = stdout; pthread_create(&a, NULL, thread1, NULL); pthread_create(&b, NULL, thread2, NULL); pthread_join(a, NULL); pthread_join(b, NULL); return 0; }What real bugs look like
A study of 105 concurrency bugs in MySQL, Apache, Mozilla and OpenOffice found 74 non-deadlock bugs and 31 deadlocks. Of the non-deadlock bugs, 97% were atomicity violations like this one, or order violations: using something before another thread sets it.
Lu et al. 2008 (OSTEP fig. 32.1) application non-deadlock deadlock MySQL 14 9 Apache 13 4 Mozilla 41 16 OpenOffice 6 2 total 74 31 (105 bugs) atomicity violation check, then use, split by a switch fix: one lock around both order violation B runs before A, though A must be first fix: a condition variable (wait for A) deadlock threads wait for each other foreverAnother way: an event loop
Event-based concurrency drops the threads. One loop asks the kernel which events are ready, using select(), poll() or epoll, then runs a handler for each, one at a time. The same two jobs, print and clear, arrive as events. info points at msg again.
the loop (Python selectors, shown on the card): while True: for k, _ in sel.select(): # wait for ready events k.data(k.fileobj) # run its handler select(2) int select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout); only fds below FD_SETSIZE (1024) poll(2), epoll(7) the same job without that limit; epoll scales to many fdsOne handler at a time
The loop takes the print event and runs its handler from start to finish: check, then print msg. Only then does it run the clear handler. On one CPU nothing can cut in between, so no lock is needed.
select returns: print, clear (ready) print check info -> "msg", print msg (whole) clear info = NULL (whole) a handler is never paused for another handler, so check and use cannot be split (on one CPU) the loop as a Python program: import selectors, socket sel = selectors.DefaultSelector() info = "msg" def print_info(sock): sock.recv(8) if info is not None: # check and use run together: print("printed", info) # no handler can cut in def clear_info(sock): global info sock.recv(8) info = None print("cleared") senders = [] for handler in (print_info, clear_info): a, b = socket.socketpair() sel.register(a, selectors.EVENT_READ, handler) senders.append(b) for s in senders: # events arrive: print, then clear s.send(b"go") for k, _ in sel.select(): # the loop (forever, in a server) k.data(k.fileobj) prints: printed msg clearedA blocking call stalls all
A third event needs a file. Its handler calls read(), which waits for the disk. With only one thread, the whole loop waits too: a new print event sits in the inbox, unanswered, until the disk replies.
file event handler calls read(fd, buf, n) read blocks until the disk answers loop stuck inside the handler print event waits in the inbox OSTEP: if a handler blocks, "the entire server will do just that". Rule: no blocking calls in handlers. Page faults can block a handler too.Fix: asynchronous I/O
Instead the handler starts the read with aio_read(), saves what it still needs, and returns at once. The loop serves the waiting event. When the disk finishes, a completion event arrives, and a second handler finishes the job from the saved state.
file event aio_read(&cb) starts the read, returns at once saves its state: which client gets the data print event served straight away disk done aio_error(&cb) stops returning EINPROGRESS (or a signal tells the loop) done event handler looks up the saved state, sends data saving state by hand is "manual stack management"; the saved record is a continuation (OSTEP 33.7) POSIX AIO in C99 (prints 3 bytes: abc): #define _POSIX_C_SOURCE 200809L #include <aio.h> #include <errno.h> #include <fcntl.h> #include <stdio.h> #include <string.h> #include <unistd.h> int main(void) { char buf[4] = {0}; struct aiocb cb; memset(&cb, 0, sizeof cb); cb.aio_fildes = open("data.txt", O_RDONLY); cb.aio_buf = buf; cb.aio_nbytes = 3; if (cb.aio_fildes < 0 || aio_read(&cb) != 0) return 1; while (aio_error(&cb) == EINPROGRESS) { /* an event loop would serve other events here */ } printf("%zd bytes: %s\n", aio_return(&cb), buf); close(cb.aio_fildes); return 0; }Threads or events?
Threads need locks and care about order. Events need no locks on one CPU, but no handler may block, and each must save its own state. To use several CPUs, handlers run in parallel, and the locks come back.
threads events switching any time (scheduler) only between handlers shared data needs locks one CPU: no locks slow I/O thread blocks, others must not block: async keep running I/O + saved state many CPUs natural parallel handlers need locks again
أسئلة سريعة: 5
اختر إجابة واحدة لكل سؤال. يمكنك تغيير اختياراتك قبل التحقق منها.
01Thread 1 runs if (info != NULL) fputs(info, out); and Thread 2 runs info = NULL;. When can Thread 1 crash?
If Thread 2 runs first, the check sees NULL and Thread 1 skips the print. The crash needs Thread 2 to run after the check passed but before fputs uses the pointer. That window is the atomicity violation.
02What is the fix OSTEP gives for this bug?
With one lock around both pieces, Thread 2 cannot run its write while Thread 1 is between check and use: its lock call blocks until Thread 1 unlocks. Sleeps and priorities only make the bad timing rarer.
03In the study of 105 concurrency bugs that OSTEP summarises, what share of the non-deadlock bugs were atomicity or order violations?
74 of the 105 bugs were non-deadlock bugs and 31 were deadlocks. Of the 74, 97% were atomicity violations or order violations.
04Why does a basic event loop on one CPU need no locks for data its handlers share?
The loop only switches between handlers, never in the middle of one. With several CPUs running handlers in parallel, the usual locks are needed again.
05A handler in an event loop calls read() on a file that is not in memory. What happens to the other events?
There is only one thread, so a blocking call blocks everything. The fix is asynchronous I/O such as aio_read(): start the read, save what the handler still needs, return to the loop, and finish on a completion event.
المسرد
- Race
- A bug where the result depends on the order two threads happen to run in. It needs two threads using the same memory, and at least one of them writing it.
- Atomicity violation
- A bug where steps meant to happen as one, such as a check and a use, are split by another thread running in between.
- Order violation
- A bug where one thread uses something before another thread has set it up, though the code assumed the opposite order.
- Mutex (lock)
- A lock only one thread can hold at a time. A thread that asks for a held mutex blocks until the holder unlocks it.
- Event loop
- A single loop that waits for events, then runs the handler for each event, one at a time, to the end.
- select() / poll() / epoll
- System calls that let one thread wait on many file descriptors at once and learn which are ready. Linux recommends poll or epoll over select.
- Blocking call
- A call that does not return until its work is done, such as read() waiting for the disk. In an event loop it stalls every event.
- Asynchronous I/O
- I/O that starts now and finishes later, such as aio_read(). The program carries on and learns of completion by polling or a signal.
الملاحظات والمصادر
- 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.
- Passing NULL to fputs is undefined behaviour in C. On Linux and macOS it normally crashes the process with SIGSEGV, which is what OSTEP describes.
- The numbers are from Lu et al., "Learning from Mistakes" (ASPLOS 2008), as summarised in OSTEP chapter 32: 105 bugs, 74 non-deadlock and 31 deadlock, and 97% of the non-deadlock bugs were atomicity or order violations.
- The loop card is Python, using the standard selectors module, which picks epoll, kqueue, poll or select for the platform. A C server would call select(), poll() or epoll_wait() directly.
- POSIX AIO on Linux is implemented in user space by glibc with helper threads. Newer Linux servers often use io_uring for asynchronous file I/O instead; the idea, start now and finish on a completion event, is the same.
- 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.
- R. and A. Arpaci-Dusseau, Operating Systems: Three Easy Pieces, ch. 32: Common Concurrency Problems
- R. and A. Arpaci-Dusseau, Operating Systems: Three Easy Pieces, ch. 33: Event-based Concurrency
- Berkeley CS162, Lecture 7: Synchronization, Concurrency and Atomic Operations (event-driven server)
- MIT 6.1810 (2024), lecture notes: Locking
- Linux kernel documentation: Generic mutex subsystem
- Linux man-pages: pthread_mutex_lock(3p)
- Linux man-pages: select(2)
- Linux man-pages: epoll(7)
- Linux man-pages: aio(7)
- Python documentation: selectors, high-level I/O multiplexing
اختبار يتاح بعد الخطوة الأخيرة.