...
Code Block | ||||
---|---|---|---|---|
| ||||
struct multi_threaded_flags { unsigned int flag1 : 2; unsigned int flag2 : 2; }; struct multi_threaded_flags flags; int thread1(void *arg) { flags.flag1 = 1; return 0; } int thread2(void *arg) { flags.flag2 = 2; return 0; } |
The C Standard, 3.1417, paragraph 3 [ISO/IEC 9899:20112024], states
NOTE Note 2 to entry: A bit-field and an adjacent non-bit-field member are in separate memory locations. The same applies to two bit-fields, if one is declared inside a nested structure declaration and the other is not, or if the two are separated by a zero-length bit-field declaration, or if they are separated by a non-bit-field member declaration. It is not safe to concurrently update two non-atomic bit-fields in the same structure if all members declared between them are also (non-zerononzero-length) bit-fields, no matter what the sizes of those intervening bit-fields happen to be.
For example, the following instruction sequence is possible:
...
Code Block | ||||
---|---|---|---|---|
| ||||
struct multi_threaded_flags { unsigned char flag1; unsigned char flag2; }; struct multi_threaded_flags flags; int thread1(void *arg) { flags.flag1 = 1; return 0; } int thread2(void *arg) { flags.flag2 = 2; return 0; } |
Unlike C99, C11 and C23 explicitly defines define a memory location and provides the following note in subclause 3.14.17 paragraph 2 [ISO/IEC 9899:20112024]:
NOTE Note 1 to entry: Two threads of execution can update and access separate memory locations without interfering with each other.
It is almost certain that flag1
and flag2
are stored in the same word. Using a compiler that conforms to C99 or earlier, 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. The other flag will contain its previous value because both members are represented by the same word, which is the smallest unit the processor can work on. Before the changes were made to the C Standard for C11, there were no guarantees that these flags could be modified concurrently.
...
Bibliography
[ISO/IEC 9899:20112024] | 3.1417, "Memory Location" |
...