When playing around a bit with a multithreaded application (one logic thread, and one physics thread), I came upon a situation where I'd need to use a mutex on a constant member function to keep the call's result consistent.
class foo
{
private:
// Mutual class access
CMutex mutex;
// Example members
// May be changed at any time by another thread
int a;
int b;
public:
// Access calls, used by another thread
void SetA(int in_a)
{
mutex.Acquire();
a = in_a;
mutex.Release();
}
void SetB(int in_b)
{
mutex.Acquire();
b = in_b;
mutex.Release();
}
// Constant observer call
// Needs the mutex so a and b are not changed while placing
// them into the storage object
void GetFooStuff(stuffstorageclass &stuffstorage) const
{
// Gives a compile error, since the call is const
mutex.Acquire();
stuffstorage.a = a;
stuffstorage.b = b;
// Dito
mutex.Release();
}
}
The function itself is a simple observer call, which fills a structure passed in via parameter with values from the object instance. The appropriate values may also be changed at any time because of another thread. Consequently, I use a mutex to synch access to the instance.
However, since the member function is just an observer, I'd hate to make it non-const. Yet, the mutex is a member variable too, and needs to be set.
I can't make the mutex const for obvious reasons.
Now, long text, small question =)
Is this (general) situation a good place to use the "mutable" keyword, to allow mutexing for observer calls ? I'm just asking because I heard that mutable variables are a sign of bad code layout.
If so, are there any obvious improvements to the code above I might have overlooked ?
Thank you for your time,
Cheers,
- Wernaeh












