Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Bit-fields may be used to declare struct members that use only a specified number of bits. If multiple threads are accessing or making modifications to different bit-fields, a race condition may be present, because the architecture may not be able to modify only the bits to which the member currently being modified member may refer. As a result, a mutex protecting all bit-fields at the same time must be used.

...

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 that 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.

...

Even though each thread is modifying a separate bit-field, they are both modifying the same location in memory.  This is the same problem discussed in POS00-A. Avoid race conditions with multiple threads but is harder to diagnose, because it is not obvious at first glance that the same memory location is being modified.

...

This compliant solution protects all usage of the flags with a mutex, preventing an unfortunate thread scheduling interleaving from being able to occur.   In addition, the flags are declared volatile to ensure that the compiler will not attempt to move operations on them outside the mutex.

...