what goes wrong with barrier free atomic_load/store?
Tim Kientzle
kientzle at freebsd.org
Tue May 3 22:26:23 PDT 2005
> On Wednesday 20 April 2005 04:39 pm, John Giacomoni wrote:
>
>>can someone give me an example of a situation where one needs to use
>>memory barriers to ensure "correctness" when doing writes as above?
One basic example:
struct foo *p = malloc(sizeof(struct foo)); // Step 1
p->bar = 0; // Step 2
atomic(global_p = p); // Step 3
This is a pretty common idiom: Allocate a new
data structure, initialize it, then assign the pointer
to a shared global value so that the fully-initialized
structure becomes visible all at once.
Many people miss an important detail:
A barrier is needed just before the
final pointer assignment. Otherwise, the
pointer might reach shared memory (Step 3) before
the initialization in Step 2 happens.
(This can happen because of compiler reordering
or processor write caching.)
Variations of this plagued the early attempts
to correctly define Java's threading primitives.
(It was possible to crash a lot of early JVMs
by creating new objects in one thread and
accessing them in another; every now and then
the accessing thread would see an uninitialized
vtable and crash the entire JVM.)
Tim Kientzle
More information about the freebsd-hackers
mailing list