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
中的函数,从而更改 的值,
?1
行是否必要>栏
请注意,int
在这里可以是任何类型。
最佳答案
当您返回引用时,在这种情况下锁定对您来说完全没用。当您使用返回的引用时,您可能需要锁定。
但是,如果您要返回一个值,它将产生更大的影响,请查看 this一个撕裂阅读的例子。
关于c++ - 锁定互斥锁以仅返回一个值是否明智?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25352351/