如何在初始化列表中锁定互斥锁?

Dav*_*vid 8 c++ multithreading c++11

我有一个ConcurrentQueue基于用户提供的容器的类,有一个像这样的构造函数...

ConcurrentQueue(const ConcurrentQueue& other) : m_Queue(other.m_Queue) {}
Run Code Online (Sandbox Code Playgroud)

但是,我需要other在复制时锁定互斥锁.

选项1:

所以我根本不能使用复制构造函数,并且......

ConcurrentQueue(const ConcurrentQueue& other) : m_Queue(other.m_Queue)
{
    std::lock_guard<std::mutex> lock(other.m_Mutex);
    m_Queue = other.m_Queue;
}
Run Code Online (Sandbox Code Playgroud)

但我不能保证复制分配和复制构造是等效的功能.

选项2:

我可以有私人方法......

std::queue<T, Container> GetQueue() const
{
    std::lock_guard<std::mutex> lock(other.m_Mutex);
    return m_Queue;
}
Run Code Online (Sandbox Code Playgroud)

然后在构造函数中执行此操作...

ConcurrentQueue(const ConcurrentQueue& other) : m_Queue(other.GetQueue()) {}
Run Code Online (Sandbox Code Playgroud)

但这可能(取决于优化)使用m_Queue的复制构造函数一次,并且它的移动构造函数一次.我也不能保证副本和移动只相当于副本.此外,用户提供的容器可能是奇怪的并且是可复制的但是不可移动的,这也会导致这种方法出现问题.

那么,我该怎么办?

Jam*_*nze 9

ConcurrrentQueue::ConcurrrentQueue(
        ConcurrrentQueue const& other )
    : m_Queue( (std::lock_guard<std::mutex>( other.m_Mutex ),
               other.m_Queue ) )
{
}
Run Code Online (Sandbox Code Playgroud)

应该管用.