Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is sizeof(std::mutex)==40 (gcc,clang,icc)? [duplicate]

Tags:

c++

c++11

mutex

rather than sizeof(std::atomic<bool>)==1 ?

A mutex could be implemented via a simple std::atomic<bool>, so I would think that the size of a mutex could be as small as that, or perhaps 4 (32bits).

like image 972
Walter Avatar asked May 22 '13 14:05

Walter


2 Answers

With one bool you could only implement a spin-lock. Note that it would be an unfair lock because nothing ensures that waiters queue up, so there is a chance that under high contention in the most extreme case a thread could be blocked forever because it would always lose the race to acquire the lock.

A mutex implementation needs support from the operating system to be able to put the waiting threads to sleep. So, a mutex would need a flag telling whether it is locked and some form of a queue descriptor that allows putting waiting threads to sleep and waking them. If you want the mutex to be able to support recursive locking, robustness, optional spinning, priority inversion protection, etc.., it would need even more members.

like image 129
Maxim Egorushkin Avatar answered Oct 18 '22 03:10

Maxim Egorushkin


The GNU library usually uses Posix threads to implement the standard thread library. That uses a single type pthread_mutex_t to represent several different types of mutex; so it contains various fields needed for more complex mutexes (e.g. a counter for recursive mutexes), plus a field to specify the type.

You're right that, in principle, with suitable support from the operating system, a std::mutex could use as little as one byte of user memory. (On Linux, it has to be an int; and on other platforms, it might be an integer or pointer-sized handle to a kernel resource). Presumably, the benefits of using a well-tested existing implementation were deemed to outweigh the benefits of saving a few dozen bytes per mutex.

like image 23
Mike Seymour Avatar answered Oct 18 '22 03:10

Mike Seymour