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.
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With