c++ - 锁定互斥锁以仅返回一个值是否明智?

标签 c++ multithreading thread-safety mutex

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/

相关文章:

java - 无法在 Java 中停止线程

C程序: Parent read one file and child count the number of words.子程序有4个线程并且还使用了mapper和reducer

c++ - 模板、嵌套类和 "expected constructor, destructor, or conversion before ' &' token"

c++ - Nginx 代理后面的 C++ 守护进程的 FastCGI 或 HTTP 服务器

c++ - C++11 std::atomic 是否保证互斥和顺序一致性?

c# - 使用锁是否比使用本地(单个应用程序)信号量具有更好的性能?

Java SecureRandom 围绕创建和重新播种的正确用法

python - 线程锁-何时真正需要?

c++ - 如何通过 yaml-cpp 加载 YAML 文件?

c++ - C中函数的局部变量范围