Is it correct to access non-atomic variables using atomic operations?

Hi Everyone,

  This might be more a C/C++11 question than a LLVM question: I wondering if it is semantically correct to access an ordinary variable via atomic operations, like:

int val;
void foo(){ atomic_store((atomic_int *)(&val), 42); }

  I tried this simple program on clang+llvm and 42 seems to be correctly stored to val. But, is this just by luck or a right way to go?

Thanks.

- Lei

Strictly speaking, it's undefined behavior; in practice, it'll do what
you expect (with the disclaimer that it's generally a bad idea to mix
atomic and non-atomic accesses to a variable).

-Eli

Like with nearly all type punning, alias analysis is likely to eat
your program if you do this.

In LLVM itself, atomic operations are simply a different kind of
operation on ordinary addresses. Running an atomic operation and a
non-atomic operation on the same address concurrently, where at least
one of the operations is a write, is a data race, which gives 'undef'
results, but as long as you separate your non-atomic operations from
other operations with happens-before edges, you'll be fine:
http://llvm.org/docs/LangRef.html#memmodel.

I don't think Clang exposes any way to get at the raw LLVM operations
from C++, which I think is probably the right design. Why do you think
you want to access an ordinary variable with atomic operations instead
of just defining atomic variables?

Jeffrey

Thanks a lot for the detailed explanation. There is no particular reason that I want to do this way. The question just comes when I am trying to get to understand the usage of C/C++11 atomics.

- Lei