Mixing C++11 atomics and OpenMP

Andrew Haley aph@redhat.com
Sat Dec 24 11:29:00 GMT 2016


On 24/12/16 11:00, Michael Underhill wrote:

> OpenMP has its own support for atomic access, however, there are at
> least two reasons for preferring C++11 atomics: they are significantly
> more flexible and they are part of the standard. Does GCC implement
> C++11/14/17 atomics and OpenMP in a way so that they can be combined?

In practice, yes.

OpenMP uses a fence-based relaxed memory model, so an atomic operation
isn't guaranteed to be visible to other threads until you do a FLUSH
(or a LOCK/UNLOCK) in both reading and writing threads.  Also, there
are no ordering guarantees except that FLUSH directives are executed
in a single total order.  An OpenMP atomic op is equivalent to the
same C++ atomic operation with memory_order_relaxed.  A FLUSH is, I
think, equivalent to atomic_thread_fence(memory_order_seq_cst).  I
also believe that an atomic_thread_fence(memory_order_seq_cst) in one
thread will synchronize quite happily with a FLUSH in another, but I
don't know that this is formally required.

The trick is not to try to be too cute by using OpenMP operations in
one thread and hoping that they will synchronize with weaker C++11
atomic operations in another thread.  It might work on one machine but
not another.

Andrew.



More information about the Gcc-help mailing list