[cpp-threads] C++ memory model

Peter Dimov pdimov at mmltd.net
Wed Sep 23 01:17:12 BST 2009


Boehm, Hans wrote:

> What about
>
> atomic<int> x;
>
> Thread 1:
> <reads x now and then, but doesn't write it>
>
> Thread 2:
> for (;;) x = 17;
>
> Assume the compiler can deduce that there are no other threads
> writing to x.
>
> Does the above sentence prevent the compiler from transforming the
> thread 2 code to:
>
> x = 17; for (;;);      ?
>
> Strictly, I think the answer is "yes".

Yes, it is.

> But I don't think there's any way the program can tell.

Correct. Is this a problem? Is anyone concerned about denying the compiler 
this valuable optimization opportunity? :-)

> What does a prohibition on program
> transformations mean in light of the "as if" rule?

Nothing, really. It has no theoretical meaning. I can look at the generated 
code, see that the compiler has moved the store out of the loop, submit a 
bug report, and we can then have a lively debate with the compiler writers 
in the bug comments about the sentence. In theory, none of that matters. In 
practice, it does.

> If this is allowed under the "as if" rule, am I allowed to justify a
> transfomation to
>
> for (;;){} x = 17;
>
> by arguing that if you wait for 20 years and nothing happened, the
> behavior is as if this thread just hadn't made progress for 20 years,
> which is allowable behavior?

In principle, you can compile all threads to for(;;); and make the same 
argument.

> Alternatively, is it OK to implement this on a machine with a store
> buffer that gets flushed only on overflow, and since there are no
> stores except to x, the buffer never gets flushed?  (Or I might have
> an interpreter that exhibits this behavior.)

If you have such a machine (it would need to have a smart store buffer that 
collapses repeated stores), then I think that it would be OK, as it just 
replicates the hardware behavior in software. But there's no point in doing 
so.




More information about the cpp-threads mailing list