260*_*607 2 c++ multithreading boost mutex boost-thread
我有一个由多个线程共享的对象,我想锁定单个成员变量,而不锁定整个对象,以便不同的线程可以同时访问不同的成员变量.阅读完一些文章后,我使用shared_mutex和getter()/ setter()函数编写代码.
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.
......
Run Code Online (Sandbox Code Playgroud)
代码看起来很笨拙,特别是当成员变量的数量增加时.我想知道这类问题是否有更好的解决方案.
谢谢.
由于您显然只需要在实际读取/写入数据的短时间内进行锁定,因此您可以将受控数据封装到一个类型中,然后将其用作成员变量:
// note: you probably should add constructors as well
template<typename T> struct synchronized
{
public:
synchronized& operator=(T const& newval)
{
boost::unique_lock lock(mutex);
value = newval;
}
operator T() const
{
boost::unique_lock lock(mutex);
return value;
}
private:
T value;
boost::shared_mutex mutex;
};
class Test
{
public:
synchronized<double> x;
synchronized<int> y;
synchronized<std::string> z;
};
void foo(Test& t)
{
double read = t.x; // locked, via synchronized<double>::operator double() const
t.x = 3.14; // locked, via synchronized<double>::operator=
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2509 次 |
最近记录: |