Do I need to have a static lock for a static member variable of a class in C ++

I have a static map as a member variable of my class. Do we need a static lock when we need to access this card?

-1
source share
4 answers

If your instance is std::mapdeclared static, then your lock should also be static.

Consider two threads working with individual objects using a map when the lock is a non-stationary member, but a map.

  • Object 1 blocks the local lock and starts managing the shared card.
  • Object 2 locks its local lock (this is a separate lock, remember) and begins to manage the shared card.
  • Boom//

static, , , .

, , static, , .

+4

mutex , . , , .

static:

  • class static (, , ):

    class X {
      static map<A,B> mMap;
    };
    

    . , , . , .

  • local static:

     class X {
       void foo() {
         static map<A,B> theMap{ /* ... */ };
       }
     };
    

    , , foo . . . foo, static global. foo. :

     class X {
       static mutex mapMutex;
    
       static map<A,B>& getMap() {
         static map<A,B> theMap{ /* ... */ };
         return theMap;
       }
    
       void useMap() {
         lock myLock(mutex);
         getMap()[a] = b;
       }
     };
    
  • ( " " )

     static map<A,B> gMap;
    
     class X { /* ... */ };
    

    , , .. .cpp, . , , . , , . .

0

, , smth static (, <). , static .

, , , , - :

class A {
    private:
        static std::map....

    public:
        void doSomethingWithMap() {
            //lock mutex

            //some action with map

            //unlock mutex
        }
}

If this happens, you might want your mutex to be a member of this class. This is the point - it depends on the volume that you need. If you need to lock globally on all objects of this class, you should consider using a static member of the class, if you want to have a lock for each object - you should set only a member of the class.

-1
source

No, usually you do not need a static lock.

-2
source

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


All Articles