Not sure if this is a style question, or something that has a hard rule…
If I want to keep the public method interface as const as possible, but make the object thread safe, should I use mutable mutexes? In general, is this good style, or should a non-const method interface be preferred? Please justify your view.
[Answer edited]
Basically using const methods with mutable mutexes is a good idea (don’t return references by the way, make sure to return by value), at least to indicate they do not modify the object. Mutexes should not be const, it would be a shameless lie to define lock/unlock methods as const…
Actually this (and memoization) are the only fair uses I see of the
mutablekeyword.You could also use a mutex which is external to your object: arrange for all your methods to be reentrant, and have the user manage the lock herself :
{ lock locker(the_mutex); obj.foo(); }is not that hard to type, andhas the advantage it doesn’t require two mutex locks (and you are guaranteed the state of the object did not change).