Part 3 of 7 · 2 min read
Order
In plain words: A newspaper reader opens the paper before the newsagent has put it on the doorstep. The reader assumed an order that nobody ensured. The analogy stops in one place: the reader sees an empty doorstep, while a thread reading an uninitialised pointer sees whatever is in memory.
An order violation is a bug in which one operation must happen before another, and the program does not enforce it. Typically, a thread uses data that another thread is supposed to set up. The programmer assumes that the setup always runs first, because that was true in every test.
pthread_create(&t, NULL, worker, NULL); /* the worker reads table[0] */
usleep(1000); /* a slow start-up, added to show the bug */
table = calloc(4, sizeof(int)); /* too late: the worker has already run */
The worker thread uses table before main has set it. With the delay, all five test runs crashed with a segmentation fault (exit status 139). Without it, the new thread often needs some microseconds to start, and the main thread wins by luck, a result that is the same in every test and fails one day on a busier machine.
The fix is to enforce the order with synchronisation, not with timing:
- set up the data before creating the thread, since thread creation orders everything before it with everything in the new thread;
- or have the worker wait on a condition variable or a semaphore at 0 (pages 4 and 5) that the main thread posts after the setup;
- or join a thread that does the setup first.
Order violation
An order violation is a concurrency bug in which one operation is assumed to occur before another, such as initialisation before use, but nothing in the program forces that order, so a different interleaving reverses it.
Example: a thread reads a table before the main thread allocates it, because the program relied on the new thread being slow to start.
Check yourself: 1. What did the worker assume? 2. Why does thread creation itself give a safe order? 3. Name two ways to enforce an order.