...
Code Block | ||
---|---|---|
| ||
struct multi_threaded_flags { int flag1 : 2; int flag2 : 2; }; struct multi_threaded_flags flags; void thread1(void) { flags.flag1 = 1; } void thread2(void) { flags.flag2 = 2; } |
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 which ends with the 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 could work on.
...
Code Block | ||
---|---|---|
| ||
struct multi_threaded_flags { volatile int flag1 : 2; volatile int flag2 : 2; pthread_mutex_t mutex; }; struct multi_threaded_flags flags; void thread1(void) { pthread_mutex_lock(&flags.mutex); flags.flag1 = 1; pthread_mutex_unlock(&flags.mutex); } void thread2(void) { pthread_mutex_lock(&flags.mutex); flags.flag2 = 2; pthread_mutex_unlock(&flags.mutex); } |
...