Versions Compared

Key

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

Inside of a struct you may define a bit field any way that you want, however when compiling on different compilers the results of the bitfield layout may vary. It is implementation defined as to a declared int bit field is actually treated as a signed or unsigned int bit-field.whether or not the bit field has a lo-hi or hi-lo ordering of bits.

In the following code, despite using a mutex to lock the flag bit defined in the foo struct, it is in general impossible to load the flag and counter fields seperatly, thus a mutex would have to be used when accessing either field in the struct in order for it to be thread safe. In addition, in the code below, it is implementation defined as to if flag and counter are signed or unsigned ints.

Code

Code Block
bgColor#FFcccc

struct foo {
	int flag : 1;
	int counter : 15;
};

struct foo my_foo;
...
pthread_mutex_lock(&my_mutex);
my_foo.flag = !my_foo.flag;
pthread_mutex_unlock(&my_mutex);

my_foo.counter++;

Wiki Markup
*Sources:*
[http://en.wikipedia.org/wiki/Bit_field]
http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1124.pdf \[Section 6.7.2.1\]