如何使用互斥体正确编写多线程代码:
std::mutex m, m2;
... thread
m2.lock();
if ((++reference) == 1) m.lock();
m2.unlock();
... differenet thread
m2.lock();
if ((reference--) == 0) m.unlock(); // error here
m2.unlock ();
当我调用 m.unlock() 时,visual studio 2012 引发错误 R6010。 Mutex m2 工作正常,因为它在一个线程中锁定和解锁。
我尝试用 std::contidional_variable 替换代码,但它在开始时没有收到通知,第一次进入 cond_var.wait_one 会无限等待。
UPD:替换为 conditional_variable,现在一切正常。文章:C++0x has no semaphores? How to synchronize threads?
最佳答案
Mutex 需要由拥有线程(锁定它的线程)解锁:
If the mutex is not currently locked by the calling thread, it causes undefined behavior. (http://www.cplusplus.com/reference/mutex/mutex/unlock/)
您需要使用条件变量——我认为围绕它构建一个信号量实现对您来说会很好。在此处查看已接受的答案:C++0x has no semaphores? How to synchronize threads?
关于c++ - 如何在不同线程中使用 std::mutex?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39674550/