...
The data race can be disabled by declaring the data to be volatile, because the volatile keyword forces the compiler to not produce two reads of the data.
However, this violates [CON03violates CON02-C. Do not use volatile as a synchronization primitive.
| Code Block | ||||
|---|---|---|---|---|
| ||||
#include <stdio.h>
#include <stdlib.h>
void doStuff(volatile int* ps) {
printf("NON-VOLATILE");
switch (*ps) {
case 0: {printf("0"); break;}
case 1: {printf("1"); break;}
case 2: {printf("2"); break;}
case 3: {printf("3"); break;}
case 4: {printf("4"); break;}
default: {printf("default"); break;}
}
}
|
Compliant Solution (C11, Atomic)
Declaring the data to be atomic also forces the compiler to produce only one read of the data.
| Code Block | ||||
|---|---|---|---|---|
| ||||
#include <stdio.h> #include <stdlib.h> #include <stdatomic.h> void doStuff(atomic_int* ps) { printf("NON-VOLATILE"); switch (atomic_load(ps)) { case 0: {printf("0"); break;} case 1: {printf("1"); break;} case 2: {printf("2"); break;} case 3: {printf("3"); break;} case 4: {printf("4"); break;} default: {printf("default"); break;} } } |
...