单线程可以双锁互斥锁吗?

Gif*_*guy 7 c++ multithreading mutex

如果我想让一个线程暂停一段时间,直到满足某些条件,我可以双重锁定互斥锁吗?

这是我现在正在使用的想法的一个基本示例:

class foo
{
public:
    static std::mutex processingMutex;

    void infinite_processing_loop()
    {
        processingMutex.lock();  // Lock the mutex, initially

        while(true)
        {
            if ( /*ready for this thread to process data*/ )
            {
                // ... perform one round of data processing ...
            }
            else  // NOT ready for this thread to process data
            {
                /* Pause this thread,
                   and wait for another thread to unlock this mutex
                   (when more data might be ready for processing) */

                processingMutex.lock();
            }
        }

        processingMutex.unlock();  // Will never be executed
    }
};
Run Code Online (Sandbox Code Playgroud)

当处理线程尝试双重锁定互斥锁时,它会停止吗?
另一个线程是否可以解锁相同的互斥锁,从而导致暂停的处理线程恢复?

还是会std::mutex自动识别何时从同一处理线程锁定互斥锁两次?

sel*_*bie 6

std::mutex通常会在所有者线程第二次尝试锁定时死锁。即使没有,它也被视为应用程序尝试使用此原语的错误。

std::recursive_mutex将允许重入锁。所以如果你加锁两次,你需要在互斥锁被其他线程抢到之前解锁两次。

有一种观点认为,任何涉及在互斥锁被锁定后递归获取互斥锁的设计都是设计缺陷。我会尝试挖掘该线程并添加它。