2016-09-24 39 views
2

如何正确编写多线程代码使用互斥:如何在不同的线程中使用std :: 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?

+0

还有什么地方在您的程序中锁定/解锁互斥锁。 – v78

+0

在第三个线程中,这个互斥锁是锁,做一些工作并解锁。在这个线程里面一切都很好。 我评论过它,没有任何变化(错误R6010提出)。 – Alexey

+0

请注意,“reference”增量和减量周围的括号不是必需的(并且分散注意力)。 –

回答

相关问题