Mixing C++11 atomics and OpenMP Mixing C++11 atomics and OpenMP multithreading multithreading

Mixing C++11 atomics and OpenMP


Update:

OpenMP 5.0 defines the interactions to C++11 and further. Among others, it says that using the following features may result in unspecified behavior:

  • Data-dependency ordering: atomics and memory model
  • Additions to the standard library
  • C++11 library

So clearly, mixing C++11 atomics and OpenMP 5.0 will result in unspecified behavior. At least the standard itself promises that "future versions of the OpenMP specification are expected to address [these] features".

Old discussion:

Interestingly, the OpenMP 4.5 standard (2.13.6) has a rather vague reference to C++11 atomics, or more specific std::memory_order:

The intent is that, when the analogous operation exists in C++11 or C11, a sequentially consistent atomic construct has the same semantics as a memory_order_seq_cst atomic operation in C++11/C11. Similarly, a non-sequentially consistent atomic construct has the same semantics as a memory_order_relaxed atomic operation in C++11/C11.

Unfortunately this is only a note, there is nothing that defines that they are playing nicely together. In particular, even the latest OpenMP 5.0 preview still refers to C++98 as the only normative reference for C++. So technically, OpenMP doesn't even support C++11 itself.

That aside, it will probably work most of the time in practice. I would agree that using std::atomic has less potential for trouble if used together with OpenMP than C++11 threading. But if there is any trouble, it may not be as obvious. Worst case would be a atomic that doesn't operate atomically, even though I have serious trouble imagining a realistic scenario where this may happen. At the end of the day, it may not be worth it and the safest thing is to stick with pure OpenMP or pure C++11 thread/atomics.

Maybe Hristo has something to say about this, in the mean time check out this answer for a more general discussion. While a bit dated, I'm afraid it still holds.


This is currently unspecified by OpenMP 4.5. In practice, you can use C++11 atomic operations with OpenMP threads in most compilers, but there is no formal guarentee that it will work.

Because of the unspecified behavior, GCC did not support C11 atomics (which are nearly identical in semantics to C++11 atomics) and OpenMP threads until recently. See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=65467 for details.

OpenMP 5.0 made an attempt to address this. The normative language references were updated to C11 and C++11. However, the atomics and memory model from these is "not supported", which means implementation-defined. I wish OpenMP 5.0 said more but it is extremely difficult to define the interaction of OpenMP and ISO language atomics.