I have an object which is shared by multiple threads, I want to lock individual member variables, without locking the entire object, so that different threads can access to different member variables at the same time.
After reading some articles, I write the code using shared_mutex and getter() / setter() functions.
class Test
{
public:
**// variable, shared_mutex and getter/setter for x**
double x;
boost::shared_mutex x_mutex;
double x_getter();
void x_setter();
**// variable, shared_mutex and getter/setter for y**
......
**// variable, shared_mutex and getter/setter for z**
......
};
double Test::x_getter()
{
// get shared access
boost::shared_lock lock(_access);
return x;
}
void Test::x_setter()
{
// get exclusive access
boost::unique_lock lock(_access);
// do something with x;
}
//getter/setter functions for y and z.
......
The code looks clumsy, especially when the number of member variables increases. I am wondering whether there is better solutions out there for this type of problem.
Thanks.
Since you obviously need the lock only for the short time of actually reading/writing the data, you could just encapsulate it with the controlled data into a type which you then use as member variables: