flak rss random

potential thread startup race condition

As per Old New Thing, a thread can start running before the function that creates it returns. The same bug can exist in a program running on OpenBSD. (The bug is not in the thread library, but the program that calls it.) Here’s a bit of code from the body of rthread.c:pthread_create.

        _spinlock(&_thread_lock);
        LIST_INSERT_HEAD(&_thread_list, thread, threads);
        _spinunlock(&_thread_lock);

        /* we're going to be multi-threaded real soon now */
        __isthreaded = 1;
        rc = __tfork_thread(&param, sizeof(param), _rthread_start, thread);
        if (rc != -1) {
                /* success */
                *threadp = thread;
                return (0);
        }

Notice that we have to put the newly allocated thread structure in the thread list before the thread itself exists, otherwise we’d be subject to the race ourselves.

The old pthread regress tests had several examples of exactly this bug because they were written against a cooperative multithreaded library. Finding and fixing those was just a little bonus fun I had while trying to track down early bugs in rthreads.

Posted 26 Oct 2013 00:19 by tedu Updated: 26 Oct 2013 00:34
Tagged: c openbsd programming