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

标签 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

这看起来在 Linux 上工作得很好,并且不需要条件变量 - 除了 C++ 标准说在同一个线程中两次获取锁是未定义的行为 - 我在线程 1 中这样做。

最佳答案

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

来自cppreferencestd::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/

相关文章:

java - 对单个静态整数索引进行多次读写会导致索引越界

c++ - 在mfc中嵌入Window Media Player

c++ - 复合赋值(乘法)

java - 如果无法获取锁,Hibernate LockMode 释放并快速失败

linux - flock(1) 无法释放锁

c++ - 如何允许线程 2 在我在线程 1 中打开的端口上进行通信?

c++ - 解构表达式

c++ - 引用在 try catch 中没有按预期工作

c# - .NET 中对象的锁定层次结构

java - 我应该在我的示例中同步方法吗?