c++ - 如何在不同线程中使用 std::mutex?

标签 c++ multithreading mutex

如何使用互斥体正确编写多线程代码:

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/

相关文章:

c++ - 如何在不使用数组的情况下将 chrono::time_point 转换为字符串?

c++ - 在包含名称和标记的结构中按升序对名称进行冒泡排序

c++ - CL_INVALID_COMMAND_QUEUE 问题

c++ - 在 C++ 中使用 std::Vector 进行多线程

消费者-生产者。没有错误。有时工作。为什么?

c++ - 合并 N 个保持时间顺序的日志文件

java - 从线程调用 Activity

c++ - 如何决定我需要多少个互斥体?

android - HttpEntity.getContent() 进度指示器?

c++ - "mutex"和 "lock"有什么区别?