Versions Compared

Key

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

...

In this noncompliant code example, two threads simultaneously modify two distinct members of a struct.:

Code Block
bgColor#ffcccc
langc
struct multi_threaded_flags {
  unsigned char flag1;
  unsigned char flag2;
};
 
struct multi_threaded_flags flags;
 
void thread1(void) {
  flags.flag1 = 1;
}

void thread2(void) {
  flags.flag2 = 2;
}

...

Adjacent bit-fields may be stored in a single memory location. Consequently, modifying adjacent bit-fields in different threads is undefined behavior, even in C11.:

Code Block
bgColor#FFcccc
langc
struct multi_threaded_flags {
  unsigned int flag1 : 2;
  unsigned int flag2 : 2;
};

struct multi_threaded_flags flags;

void thread1(void) {
  flags.flag1 = 1;
}

void thread2(void) {
  flags.flag2 = 2;
}

The C Standard, section Section 3.14.3 [ISO/IEC 9899:2011], states:

...

[ISO/IEC 9899:2011]Section 3.14, "Memory Location"

 

...