Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mixing C++11 atomics and OpenMP

Tags:

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. On the other hand, OpenMP is more powerful than the C++11 thread library.

The standard specifies the atomic operations library and the thread support library in two distinct chapters. This makes me to believe that the components for atomic access are kind of orthogonal to the thread library used. Can I indeed combine C++11 atomics and OpenMP?


There is a very similar question on Stack Overflow; however, it has been basically unanswered for three years, since its answer does not answer the actual question.

like image 861
user1494080 Avatar asked Dec 24 '16 00:12

user1494080


1 Answers

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.

like image 96
Zulan Avatar answered Sep 28 '22 09:09

Zulan