mutable mutex

Jul 11, 2017 at 9:39am
Hi

I'm working through the book "C++ Concurrency in Action" by A. Williams and would like to better understand the use of mutable mutex's.

On pg 74, listing 4.5, a mutex is declared as mutable.

The explanation he puts forward on pg 75 is - "Since locking a mutex is a mutating operation, the mutex object must be marked mutable so it can be locked in empty() and in the copy constructor."

The mutex in listing 4.5 is private.

I assumed that a mutex is modifiable anyway, so why would it be "mutable" ?

Has anybody perhaps used a mutable mutex and if so, discuss why ?
Last edited on Jul 11, 2017 at 9:40am
Jul 11, 2017 at 9:43am
The point is that, even in a const object, the mutex must be able to be locked/unlocked. So even in a const object, the mutex must be non-const. Hence, it must be declared mutable.
Jul 11, 2017 at 9:50am
so given that the constant public member function bool empty() const uses a lock_guard, which modifies the mutex, therefore the mutex must be declared as mutable ?
Jul 11, 2017 at 2:28pm
That's right.
Herb Sutter calls that "The M&M Rule": mutex and mutable go together.
Topic archived. No new replies allowed.