【发布时间】:2014-08-17 18:31:52
【问题描述】:
class Foo {
public:
// ...
const int &getBar() const noexcept;
void doSomethingWithBar(); // (2)
private:
std::mutex barMutex;
int bar = 7;
};
const int &Foo::getBar() const noexcept {
std::lock_guard<std::mutex> lock(this->barMutex); // (1)
return this->bar;
}
void Foo::doSomethingWithBar() {
std::lock_guard<std::mutex> lock(this->barMutex); // necessary here
this->bar++;
}
在线程安全方面,考虑到另一个线程可能会干扰并调用2行中的函数,从而改变bar的值,是否需要行1?
请注意,int 在这里可能是任何类型。
【问题讨论】:
-
您担心的是错误的事情。第 (1) 行既没有帮助也没有伤害,因为下一行从不读取
bar的值。竞争条件将发生在调用代码中,它可能会通过您返回的引用读取值,没有保护。 -
@Igor 错了,第 1 行为我们提供了重要的可见性保证!
-
@Voo:它保证什么变化的可见性?
-
此外,返回
const int &几乎总是毫无意义的。 -
如果类是完全线程安全的,那么
barMutex的目的是什么?为什么要给已经在内部执行必要同步的类添加一层外部同步?
标签: c++ multithreading thread-safety mutex