13

[thread.mutex.class]/3:

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

What is the reason for this requirement?

Alex Guteniev
  • 12,039
  • 2
  • 34
  • 79
  • 1
    Wild guess : it may be for compatibility with preexisting threading libraries like pthread? Just about every threading library before `std::mutex` had a C API. – François Andrieux Nov 03 '21 at 14:53
  • Another guess: every compiler's implementation of std mutex was a standard layout class, so why not require it? – Yakk - Adam Nevraumont Nov 03 '21 at 14:53
  • @Yakk-AdamNevraumont, but what benefits? (Except maybe making some standard library implementations jump thru the hoops to keep this property (I'm not kidding)) – Alex Guteniev Nov 03 '21 at 14:57
  • @FrançoisAndrieux, actually you may be right, the intention might be to allow building pthreads interface on top of C++ mutexes... – Alex Guteniev Nov 03 '21 at 14:59
  • 1
    ABI compatibility maybe? C11 has a `mtx_t` (well, threading support in C11 is optional, but assuming it *is* there). And presumably if `std::mutex` is standard layout, and it has a `mtx_t` member, then they are pointer-interconvertible. Such things have precedent. `std::complex` and the C11 `_Complex` specifier (explicitly binary compatible). Then there's `std::atmoic` and the C11 `_Atomic` specifier. – StoryTeller - Unslander Monica Nov 03 '21 at 15:09

1 Answers1

11

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.
dfrib
  • 70,367
  • 12
  • 127
  • 192