You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 5 Next »

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

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++;

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]

  • No labels