我有一个线程需要被阻塞,直到另一个线程发生某些事情。这听起来很典型,我有这个解决方案。
//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
这看起来在 Linux 上工作得很好,并且不需要条件变量 - 除了 C++ 标准说在同一个线程中两次获取锁是未定义的行为 - 我在线程 1 中这样做。
最佳答案
标准的 std::mutex 不能被锁定它的线程以外的线程解锁。这是未定义的尝试行为。
来自cppreference在 std::mutex::unlock
上:
Unlocks the mutex.
The mutex must be locked by the current thread of execution, otherwise, the behavior is undefined.
因此,您提出的策略不适用于 std::mutex
。
关于C++ 使用互斥体在两个线程之间同步,而不使用条件变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59078389/