【发布时间】:2015-09-06 08:58:00
【问题描述】:
让我们在 C++ 中考虑这样一个类:
class CuteClass
{
public:
int getFancyInt() const;
float getNiceFloat() const;
string getPerfectString() const;
void setIntSomething(int something);
void setInternalState(State newState);
};
这个类的实例可以从几个不同的线程同时访问。然后:
所有 getMethods(getFancyInt、getNiceFloat、getPerfectString)不应相互阻塞。它们不会改变对象的内部状态。
所有的 setMethod(setIntSomething, setInternalState) 应该:
- 互相阻止 - 避免对象状态不一致,
- 阻止所有 getMethods - 以避免返回部分更改的数据,
- 被所有 getMethods 阻止 - 以避免返回部分更改的数据。
带有互斥锁的简单 lock_guard 将满足除一个之外的所有要求 - getMethod 然后会阻止其他 getMethods。
在这种情况下,哪种解决方案既简单又干净?
【问题讨论】:
-
Reader/Writer Locks in C++ 的可能重复项
标签: c++ c++11 concurrency mutex