Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is std::mutex a standard-layout class?

[thread.mutex.class]/3:

[...] It is a standard-layout class ([class.prop]).

What is the reason for this requirement?

like image 886
Alex Guteniev Avatar asked Nov 03 '21 14:11

Alex Guteniev


People also ask

What is the role of std :: mutex?

std::mutex A mutex is a lockable object that is designed to signal when critical sections of code need exclusive access, preventing other threads with the same protection from executing concurrently and access the same memory locations.

Why mutex is used in C++?

C++ mutax class is used to prevent our critical code to access from the various resources. Mutex is used to provide synchronization in C++ which means only one thread can access the object at the same time, By the use of Mutex keyword we can lock our object from being accessed by multiple threads at the same time.

Is std :: mutex movable?

By design, std::mutex is not movable nor copyable. This means that a class A holding a mutex won't receive a default move constructor.

Does C++ have mutex?

In C++, we create a mutex by constructing an instance of std::mutex, lock it with a call to the member function lock(), and unlock it with a call to the member function unlock().


1 Answers

Interoperability with the associated C interface. From N2320 (Multi-threading Library for Standard C++):

The C level interface has been removed from this proposal with the following rationale:

  • As long as we specify that the key types in this proposal are standard-layout types (which we have done), WG14 is still free to standardize a C interface which interoperates with this C++ interface.
  • WG14 is in a better position to solve the cancellation interoperability problem than WG21 is. [...]
  • WG14 asked WG21 to take the lead on this issue. We feel we can best take lead by specifying only a C++ interface which has the minimum hooks in it to support a future C interoperating interface (i.e. types are standard-layout types). We feel we should stop short of actually specifying that C interface in the C++ standard. WG14 can do a better job with the C interface and a future C++ standard can then import it by reference.
like image 68
dfrib Avatar answered Oct 07 '22 14:10

dfrib