Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does `std::mutex` and `std::lock` guarantee memory synchronisation in inter-processor code?

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?

like image 690
Walter Avatar asked Jun 08 '12 13:06

Walter


People also ask

What is the role of std :: mutex?

std::mutex The mutex class is a synchronization primitive that can be used to protect shared data from being simultaneously accessed by multiple threads.

Is std :: mutex fair?

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.


1 Answers

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)

like image 138
Cubbi Avatar answered Oct 02 '22 22:10

Cubbi