c++通过对不同实例的引用传递互斥锁

C++ Pass Mutex By Reference for Different Instances

本文关键字:引用 实例 c++      更新时间:2023-10-16

我想在一个类的不同实例之间共享一个互斥锁,这些实例的函数作为线程运行。我这样写对吗?(我认为我不需要使用shared_mutex,尽管这可能是更好的实践。我要用同样的方式传递它吗?)

class A
{
 public:
     // Execute some work that locks some piece of data by acquiring the mutex.
     void execute(std::mutex & myMutex);
}
class B
{
 public:
     void execute(std::shared_ptr<A> a)
     {
        //   Create the Threads for execution.
        //   Changed to correct syntax.
        std::thread t1(&B::runThread, this, a);
        std::thread t2(&B::runThread, this, a);
        t1.join();            
        t2.join();
     };
     void runThread(std::shared_ptr<A> a)
     {
         a->execute(std::ref(theMutex));
     }

 private:
 //   The Mutex to share with the threads.
 std::mutex theMutex;
}

首先,所发布的代码无法编译:B::runThread()是非static成员,因此接受隐式对象作为参数。您需要使用如下命令创建线程:

std::thread t(&B::runThread, this, a);

假设B::theMutex在使用A::execute()时适当地保护了多线程之间共享的资源,那么在不同线程之间共享互斥锁的方法就是互斥锁的用途。由于这个问题缺乏任何细节,因此无法回答互斥锁是否是合适的同步原语:根据A::execute()中的实际使用情况,其他方法可能更适合避免序列化,死锁等。

使用std::shared_mutex基本上在所有情况下都是错误的方法,当然不是"更好的做法"。std::shared_mutex实际上导致更好的方法的情况非常罕见。在实践中,我从未见过使用std::shared_mutex之类的东西会提高性能的情况(我没有在实际情况中看到std::shared_mutex,但我经常遇到POSIX计数器部分或其包装器)。相反,它总是导致比使用普通std::mutex更差的性能,并且它有极其糟糕的最坏情况:当有大量更改(即排他锁)时,它经常导致整个系统的严重停滞。