More specifically, I have (simplified) the following:
union foo
{
volatile int bits;
char data[sizeof(int)*CHAR_BIT];
}
If I never access the first sizeof(int)
items of data
, can i rely on bits
working as expected?
More specifically, I have (simplified) the following:
union foo
{
volatile int bits;
char data[sizeof(int)*CHAR_BIT];
}
If I never access the first sizeof(int)
items of data
, can i rely on bits
working as expected?
Basically marking one of the field of the structure as volatile is correct. But you have to remember what volatile keyword does. It tells the compiler to not optimize access to a variable. Value is always read from memory, not from its copy in register.
As you write in comment, you are trying to make memory allocation thread safe. Unfortunately volatile doesn't guarantee that you can access it from multiple threads. If you are using 8bit CPU, access to integer value is not atomic operation so your program will not work correctly.
volatile
is in no way useful for implementing locks. I'm not speaking just theoretically; it will fail and you will have race conditions, even on single-cpu/single-core environments. The only way to make real atomic locking primitives is to write assembly using the cpu's locking primitives (for x86, the lock prefix).
Actually, there may be a way to get by with just volatile
but the only such locking mechanism I know takes O(n)
space where n
is the number of threads, which makes it pretty useless if the number of possible threads is not known in advance.