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).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With