Example 2
Another problem that can be tested is that atomic operations are actually atomic.
Problem: Verify that atomic loads and stores are actually atomic from other threads perspective.
- Initialize the atomic values to 0.
- The test function will set each atomic value to the maximum possible value, which means changing all the bits in the atomic variable.
- The inferior verify routines will check after each single stepped instruction that every atomic variable contains either 0 or the maximum possible value.
If any atomic variable ever has a different value, that means the implementation of storing the atomic value has an exposure to other threads where the value is only partially set, and the test case fails.
The test code for this could look like:
#include <stdatomic.h> #include <limits.h> atomic_int atomi = 0; atomic_char atomc = 0; /* No other work. */ void other_threads() { } /* Verify the atomic's have one of 2 values every cycle. */ int step_verify() { if (atomi != 0 && atomi != INT_MAX) return 1; if (atomc != 0 && atomc != CHAR_MAX) return 2; return 0; } /* Verify all the final values are correct. */ int final_verify() { if (atomi != INT_MAX && atomc != CHAR_MAX) return 3; return 0; } extern void done(); main() { atomic_store (&atomi, INT_MAX); atomic_store (&atomc, CHAR_MAX); done(); }