tech-kern archive

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index][Old Index]

Re: __{read,write}_once



>   - Is 'volatile' a guarantee that the compiler will emit only one
>     instruction to fetch the value?

No.  For some types, some compilers, and some architectures, it may be,
but it is implementation-dependent.  (For some types, on some
architectures, it cannot be; for example, consider a 64-bit volatile
value on an architecture without 64-bit memory access primitives.)

What volatile is designed for is to ensure that the generated code
actually accesses the value.  Consider

	count = 0;
	while (count < 10) {
		if (*register & 0x0400) count ++;
	}

If register is "uint32_t *", the compiler is permitted to - and some
will - hoist the load, effectively turning this into

	count = 0;
	temp = *register;
	while (count < 10) {
		if (temp & 0x0400) count ++;
	}

which is unlikely to do what you want.  If register is instead declared
"volatile uint32_t *", then *register is volatile and thus must be
accessed each time through the loop.

volatile also compels such caching in some circumstances; for exmaple,
if the code is

	uint32_t *register;
	uint32_t v;
	v = *register;
	call((v+4)*v);

then, under certain circumstances (for example, v is auto and its
address is never taken) the compiler is permitted to turn that into

	call(((*register)+4) * *register)

and, on some architectures, that would be a win.  (It's less likely to
happen than the other way around, but, if addressing modes are cheap,
registers are few, and memory is fast compared to CPU cycles, the
compiler may do that.)  But make it "volatile uint32_t *register;" and
such an optimization is not permitted.

>   - Assuming there is only one instruction, strictly speaking the
>     fetch is not guaranteed to be atomic, is that correct?

Right.  What is or isn't atomic is architecture-dependent; there is, I
think, _nothing_ you can do in C that can guarantee atomicity (or, for
that matter, guarantee non-atomicity), since atomicity is fundamentally
an architecture-dependent notion.

/~\ The ASCII				  Mouse
\ / Ribbon Campaign
 X  Against HTML		mouse%rodents-montreal.org@localhost
/ \ Email!	     7D C8 61 52 5D E7 2D 39  4E F1 31 3E E8 B3 27 4B


Home | Main Index | Thread Index | Old Index