Part 2 of 7 · 2 min read
Atomicity
In plain words: A clerk looks at a shelf, sees one box, walks to fetch a form, and comes back to find another clerk took the box. The look and the take were one idea in the clerk's mind and two steps in practice. The analogy stops in one place: the clerk notices the box has gone, and a program that follows a null pointer crashes without warning.
An atomicity violation is a bug in which a sequence of operations that the programmer meant to be indivisible can be interleaved with another thread's operations. A study of real bugs in widely used programs (reported in OSTEP, chapter 32) found that 97 per cent of the non-deadlock concurrency bugs were of this kind or of the kind in section 2.
Here the check and the use are separated:
static struct conf *shared; /* another thread may set it to NULL */
if (shared != NULL) { /* check ... */
usleep(1000); /* (a pause for the example: the thread is descheduled) */
printf("value %d\n", shared->value); /* ... then use: shared may be NULL now */
}
| Step | Reader thread | Clearing thread | shared |
|---|---|---|---|
| 1 | tests shared != NULL: true |
valid | |
| 2 | (descheduled for 1 ms) | sets shared = NULL |
NULL |
| 3 | reads shared->value |
NULL: crash |
The test, run five times, crashed every time with a segmentation fault (exit status 139). Without the added sleep, the window is a few nanoseconds wide, and the crash would appear once in millions of runs, which is why such bugs pass testing.
The fix is to make the check and the use one critical section with a mutex, which the clearing thread takes as well:
pthread_mutex_lock(&mu);
if (shared != NULL) printf("value %d\n", shared->value);
pthread_mutex_unlock(&mu);
Atomicity violation
An atomicity violation is a concurrency bug in which a group of operations that must execute without interruption, such as checking a condition and acting on it, is interleaved with operations of another thread that invalidate the condition in between.
Example: a thread checks that a pointer is not null, is delayed, and then dereferences it after another thread set it to null.
Check yourself: 1. Which two steps were meant to be indivisible in the example? 2. Why did the test crash every time when a real program would crash rarely? 3. What is the fix?