Making std::mutex as static 是否为互斥量本身创建竞争条件

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

这可能听起来很愚蠢,但是,我有点困惑,我已经经历过这个 question,当我们研究它时,我们似乎处于同样的情况,我必须让我的 map 作为静态的,所以它对于将在单独的 threads 中创建的所有实例都是通用的,我想同步将作用于我的地图的函数,所以我想制作一个 std::mutex 作为 static 在我的 class 中,就像给定 link 中建议的答案一样。在这种情况下,获取和锁定 mutex 本身是否会出现任何竞争条件?有没有更好的方法我们可以使用 mutex

来同步 static map 上的功能

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

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

.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 class 成员变量,请执行此操作。否则,使其成为 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

没有

互斥体(和其他同步原语)是使用操作系统的支持实现的。这是他们完成工作的唯一方式。

他们执行这项工作的能力的一个直接推论是他们自己不容易出现竞争条件——互斥体上的锁定和解锁操作是原子的。

否则,它们也没有多大用处!每次你使用一个互斥量,你必须用另一个互斥量保护它,然后用另一个互斥量保护那个互斥量,依此类推,直到你有无限数量的互斥量,其中 none 个实际上实现了任何有用的东西。 :)

具有静态存储持续时间的 std::mutex 对象不会以任何方式改变这一点。大概您正在考虑 function-static 变量(假设它们还没有受到竞争条件的影响,必须同步,因为它们可能会被不同的线程同时访问;但是,理想情况下您仍然不会使用它们完全是因为它们使函数不可重入)。