Why sizeof (std :: mutex) == 40 (gcc, clang, icc)?

and not sizeof(std::atomic<bool>)==1 ?

A mutex can be implemented with a simple std::atomic<bool> , so I think the size of the mutex can be just as small, or maybe 4 (32 bits).

+6
source share
3 answers

With a single bool you can only implement direct locking. Please note that this will be an unfair block, because there is no guarantee that the waiters will stand in line, so there is a possibility that with high rivalry in the worst case, the flow may be blocked forever, because it will always lose the race to get blocking.

Mutex implementation requires operating system support to provide the ability to wait for pending threads. Thus, a mutex needs a flag indicating whether it is blocked and some form of queue descriptor that allows you to put waiting threads in sleep and wake them up. If you want the mutex to support recursive locking, reliability, an optional spinning wheel, protection against priority inversion, etc., She would need even more members.

+11
source

The GNU library typically uses Posix threads to implement the standard thread library. This uses one pthread_mutex_t type to represent several different types of mutexes; therefore, it contains various fields necessary for more complex mutexes (for example, a counter for recursive mutexes), plus a field for specifying the type.

You are right that, in principle, with suitable support from the operating system, std::mutex can use only one byte of user memory. (On Linux, it must be int , but on other platforms, it can be an integer or pointer size for a kernel resource). Presumably, the benefits of using a well-tested existing implementation were considered to outweigh the benefits of storing several tens of bytes per mutex.

+11
source

A mutex can be implemented with a simple std::atomic<bool>

This is unlikely, given that mutex::lock is the required operation, and std::atomic<bool> most likely non-blocking. You can put a while around the call to compare_exchange_strong , but this is not the same as mutex::lock , because it drops the processor for the entire waiting period.

In the general case, std::mutex much more complicated than a simple bool with a certain multi-threaded behavior, explaining its larger size, which depends on the compiler: for example, on ideof sizeof(mutex) is 24 .

+6
source

Source: https://habr.com/ru/post/945593/


All Articles