c++ - 将 std::mutex 设为静态是否会为互斥体本身创建竞争条件

标签 c++ multithreading c++11 mutex

这可能听起来很假,但是,我有点困惑,我已经经历过这个question ,当我们在相同的情况下调查它时,我必须让我的 map作为静态的,因此它将对将在单独 threads 中创建的所有实例通用我想同步将在我的 map 上起作用的功能,所以我想制作一个 std::mutex作为static在我的类里面,就像给定链接中建议的答案一样。在这种情况下,获取和锁定 mutex 会出现任何竞争条件吗?本身?有什么更好的方法可以同步 static map 上的功能吗?使用 mutex

最佳答案

Does Making std::mutex as static creates race-condition for the mutex itself

不,一个Mutex不容易受到竞争条件的影响。至于将它初始化为 static,你是安全的。

$6.7: 4: Dynamic initialization of a block-scope variable with static storage duration ([basic.stc.static]) or thread storage duration ([basic.stc.thread]) is performed the first time control passes through its declaration; such a variable is considered initialized upon the completion of its initialization. If the initialization exits by throwing an exception, the initialization is not complete, so it will be tried again the next time control enters the declaration. If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization


你说:

i thought of making a std::mutex as static in my class like what was suggested as an answer in the given link.

如果您还试图保护 static 类成员变量,请执行此操作。否则,将其设为 mutable 成员。事实上,您说 map 将全局初始化为 static 是可以的,因为作为成员变量的互斥体将遵循套件。

class Map{
public:
    Map(...){}

    std::size_t size() const{
         std::lock_guard<std::mutex> lck(m_m);
         return m_size;
     }

     iterator add(....) {
         std::lock_guard<std::mutex> lck(m_m);
         ....
         return your_iterator;
     }

     ...etc

private:
    mutable std::mutex m_m; //FREE ADVICE: Use a std::recursive_mutex instead
    ...others
};

现在:

//Somewhere at global scope:

Map mp(... ...);

// NOTES
// 1. `mp` will be initialized in a thread safe way by the runtime. 
// 2. Since you've protected all Read or Write member functions of the class `Map`,
//    you are safe to call it from any function and from any thread

关于c++ - 将 std::mutex 设为静态是否会为互斥体本身创建竞争条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38860572/

相关文章:

c++ - 使用boost从文件路径中提取直接父目录

c++ - 字符串长度

c# - 转义字符 - 有什么用

c - 如何测量openmp中每个线程的执行时间?

c++ - 带有构造函数的类的匿名 union/结构

c++ - Neon/RPi 上的 64 位 DSP 滤波性能优化

Java jsoup 使用线程不起作用

python - 如何在Python中完成线程的功能之前使其保持事件状态?

C++11 基于范围的循环 : How does it really work

c++ - 内联 char 到 std::string 的转换