I'm currently using openMP to write code running on multi-core nodes. openMP has a specific memory model which guarantees that memory is synchronised between threads running on different cores when a lock is acquired.
I consider using C++11 constructs (std::thread
with std::mutex
and std::lock
) instead of openMP (because of their larger flexibility) and wonder if/how memory synchronisation between processors is guaranteed here? And if not, how can I enforce it?
std::mutex The mutex class is a synchronization primitive that can be used to protect shared data from being simultaneously accessed by multiple threads.
On windows e.g. mutexes are mostly fair, but not always. Some implementations e.g. Thread Building Block provide special mutexes that are fair, but these are not based on the OSes native mutexes, and are usually implemented as spin-locks (which have their own caveats). Save this answer.
The standard makes the following guarantees about synchronization of std::mutex
, in §30.4.1.2[thread.mutex.requirements.mutex]/6-25
The expression m.lock() shall be well-formed and have the following semantics
Synchronization: Prior unlock() operations on the same object shall synchronize with this operation.
And, likewise,
The expression m.unlock() shall be well-formed and have the following semantics
Synchronization: This operation synchronizes with subsequent lock operations that obtain ownership on the same object.
(Where "synchronizes with" is a specific term explained in $1.10, although it's much easier to understand by reading C++ Concurrency In Action)
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