When multiple threads must access or make modifications to a common variable, they may also inadvertently access other variables adjacent in memory to the common variable. This is an artefact artifact of variables being stored compactly, with one byte possibly holding multiple variables, and is a common optimization on word-addressed machines. Bit-fields are especially prone to this behavior, since C is designed to store multiple bit-fields in one addressable byte ( or word). So This implies that race conditions may exist , not just on a variable accessed by multiple threads, but also on other variables sharing the same byte or word address.
A common means of tool for preventing race conditions in concurrent programming is the mutex. When properly observed by all threads, a mutex may provide safe and secure access to a common variable, however, it guarantees nothing regarding other variables that might be accessed when a common variable is accessed.
...
Although this appears to be harmless, it is possible ( and likely ) that flag1
and flag2
are stored in the same byte. If both assignments occur on a thread scheduling interleaving that ends with both stores occurring after one another, it is possible that only one of the flags will be set as intended and the other flag will equal its previous value. This is because both bit-fields are represented by the same byte, which is the smallest unit the processor can work on.
...
This compliant solution protects all usage accesses of the flags with a mutex, thereby preventing an unfortunate any thread scheduling interleaving from being able to occuroccurring. In addition, the flags are declared volatile
to ensure that the compiler will not attempt to move operations on them outside the mutex. Finally, the flags are embedded in a union alongside a long
int, and a static assertion guarantees that the flags do not occupuy occupy more space than the long
. This prevents any data not checked by the mutex from being accessed or modified with the bit fields.
...