...
Please keep in mind that while adding volatile will ensure that a compiler does not perform unintended reordering or optimization, it in no way guarantees synchronization between multiple threads or nor does it otherwise ward against simultaneous memory accesses.
Noncompliant Code Example
The following This noncompliant code example relies on the reception of a SIGINT signal to toggle a flag to terminate a loop.
...
However, if the value of i is cached, the while loop may never terminate. When compiled on GCC with the -O optimization flag, for example, the program fails to terminate even upon receiving a SIGINT.
Noncompliant Code Example
The following This noncompliant code example prevents the compiler from optimizing away the loop condition, by type casting the variable to volatile within the while loop.
...
By adding the volatile qualifier to the variable declaration, i is guaranteed to be accessed from its original address for every iteration of the while loop , as well as from within the signal handler.
...
The sig_atomic_t type is the integer type of an object that can be accessed as an atomic entity, even in the presence of asynchronous interrupts. The type of sig_atomic_t is implementation - defined, though it has some guarantees. Integer values from 0 through 127 can be safely stored to a variable of type sig_atomic_t safely.
Risk Assessment
Failing to use the volatile qualifier can result in race conditions in asynchronous portions of the code, causing unexpected values to be stored and leading to possible data integrity violations.
...