使用互斥锁在两个线程之间进行 C++ 同步而不使用条件变量

Scl*_*ker 2 c++ locking thread-synchronization stdmutex

我有一个线程需要阻塞,直到另一个线程发生某些事情。这听起来很典型,我有这个解决方案。

//thread 1
mux.lock();
//send work to another thread
mux.lock(); //will likely block which I want

//thread 2
//get the work sent over from thread 1
//work on it, then
mux.unlock(); //unblock thread 1 - all good
Run Code Online (Sandbox Code Playgroud)

这似乎在 Linux 上运行良好,并且不需要条件变量 - 除了 C++ 标准说在同一线程中两次获取锁是未定义的行为 - 我在线程 1 中这样做。

Fra*_*eux 5

标准std::mutex不能被锁定它的线程以外的线程解锁。尝试这是未定义的行为。

cppreference开始std::mutex::unlock

解锁互斥锁。

互斥锁必须被当前执行线程锁定,否则行为未定义。

因此,您提出的策略不适用于std::mutex.