Does std :: mutex do as static creates a race condition for the mutex itself

This may seem fictitious, but somehow confused, I went through this question , when we look at it, both of us, where in the same situation it seems, I have to make my mapstatic, so it will be common to all instances that will be created in a separate one threads, and I want to synchronize the functions that will act on my map, so I thought of creating std::mutexboth staticin my class, as what was suggested as an answer in this link .. in this case there will be some condition race to acquire and block yourself mutex? is there a better way to sync functions on static mapusingmutex

+4
source share
2 answers

Does std::mutexthe race condition for the mutex itself make the static condition

No, Mutex is not vulnerable to race conditions. And as for initializing it as staticyou are safe.

$6.7: 4: ([basic.stc.static]) ([basic.stc.thread]) ; . , , . ,


:

, std::mutex , , .

, - 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
+6

.

( ) . , .

, ; .

! , , , .. .., , .:)

std::mutex, , . , <-21 > (, , , , , , ).

+2

Source: https://habr.com/ru/post/1650723/


All Articles