Merging changes to volatile bitfield structs

John Love-Jensen eljay@adobe.com
Tue Oct 16 19:18:00 GMT 2007


Hi Phil,

A memory barrier is a completely different animal from a volatile qualifier.

Volatile means "compiler, do not perform certain optimizations on this
variable -- such as caching in a register -- because it may be modified in
ways that are non-obvious."  E.g., such as a memory mapped I/O port.

A memory barrier means "hardware, flush and synchronize your caches because
this important chunk of memory has been modified and the other caches (if
any) may be out of sync."

So volatile pertains to the compiler's ability to optimize.  Memory barrier
pertains to the hardware maintaining value fidelity across processes or
threads which may have independent local caches in multiple cores (or
multiple caches).

Using volatile alone does NOT imply or perform any sort of memory barrier.

Using memory barrier alone does NOT imply or perform any sort of disabling
of compiler optimization.

Which one is appropriate to use depends on what your needs are in your
situation.

As far as the granularity of byes or words for read-modify-write depends on
your architecture.  For example, a DEC Alpha architecture could not perform
byte read or write access, it could only perform word read and write access.
So byte manipulation caused a reading of a word, shifting the byte value to
write, masking it back into the word (in a register), and writing the word
back to memory.  (Wrecked havoc on my memory mapped I/O at first.  Learned
that lesson real quick.)

Also, the granularity of bitfields is word-based... so even though an
optimizer *MAY* be able to optimize bifield access into one nice byte
operation, it may not opt to do that.  If you really want that kind of
access on your architecture, and the compiler doesn't optimize that
particular use pattern, you may want to consider using your own
accessor/mutator routines that perform the operation using shifts and masks
instead of relying on bitfields.  (I'm not a big fan of bitfields, because
of the inherent non-portability.  But my bias against them aside, there are
other good reasons to avoid them and have finer control over your bitfields
than what is provided by the compiler.  Such reasons as guaranteed byte
access, such as you are HOPING the compiler MAY provide.)

HTH,
--Eljay



More information about the Gcc-help mailing list