ENع
←Concurrency bugs and events
Lesson S2 · Special topics

Concurrency bugs and event-based concurrency

14 min11 steps5 questionsIntermediate
About this lesson

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.

You'll learn to

Tick what you feel confident about. These self-checks do not affect your lesson score.

Fig S2 · Interactive
01 / 11

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
Loading figure…
or ← →
Read the lesson step by step
  1. 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
  2. Thread 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 fputs
  3. A 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 true
  4. Thread 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 None
  5. Fix: 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;
    }
  6. 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 forever
  7. Another 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 fds
  8. One 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
    cleared
  9. A 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.
  10. 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;
    }
  11. 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

Quiz Unlocks after the last step.