如何锁定使用具有初始化列表的构造函数的类的成员函数

how to lock a member function of a class which uses a constructor with an initialisation list

本文关键字:列表 初始化 构造函数 函数 成员 何锁定 锁定      更新时间:2023-10-16

这是一个很好的代码,它解决了如何在对象的成员函数上使用锁。

 #include <thread>
 #include <mutex>
 #include <iostream>
 class Foo
 {
 public:
      void increment()
      {
         for ( int i = 0; i < 10000000; ++i )
         {
             std::lock_guard<std::mutex> lock(mtx); //lock mtx
              ++x;
             // mtx is automatically released when lock
             // goes out of scope -> RAII
         }
     }
     void decrement()
     {
           for ( int i = 0; i < 10000000; ++i )
           {
               std::lock_guard<std::mutex> lock(mtx); //lock mtx
               --x;
              // mtx is automatically released when lock
              // goes out of scope -> RAII
          }
        }
        static int x;
        static std::mutex mtx;
  };
   int Foo::x = 0;
   std::mutex Foo::mtx;
   int main()
   {
       std::thread t1(&Foo::increment, Foo());
       std::thread t2(&Foo::decrement, Foo());
       t1.join();
       t2.join();
       std::cout << Foo::x;
    }

我的问题是,如果构造函数具有数据成员初始化列表,该如何实现。有可能吗?

如果Foo具有数据成员初始化列表,则不需要其他锁定,因为每个线程都有其自己的Foo类实例。成员初始化列表指定了直接和虚拟基次值和非静态数据成员的初始化器。

您只需要lock即可控制线程之间共享状态的一致性。像样品中的静态Foo::x一样。