这是我的源代码:
#include "stdio.h"
#include <stdlib.h>
#include <string.h>
#include "thread"
#include "mutex"
int count0=0 ,count1 =0;
std::mutex main_thread;
std::unique_lock<std::mutex> lck(main_thread, std::defer_lock);
void Function00(long millisecond){
while (true){
lck.lock();
count1++;
printf("count0:%d count1:%d \n",count0,count1);
lck.unlock();
std::this_thread::sleep_for(std::chrono::milliseconds(millisecond));
}
}
void Function01(){
std::thread th(Function00, 1000);//count per 1 s
do{
lck.lock();
count0++;
lck.unlock();
std::this_thread::sleep_for(std::chrono::milliseconds(500));//count per 0.5 s
} while (1);
}
int main(int argc, char *argv[])
{
Function01();
return 0;
}
然后我使用该命令构建我的.o文件:
g ++ -std = c ++ 11 -pthread testa.cpp -o a.o
但是,它显示错误:
terminate called after throwing an instance of 'std::system_error'
what(): Resource deadlock avoided
Aborted
我感到困惑,不知道要解决它,所以我尝试使用Microsoft VS2013,它运行时没有错误......我感到困惑。这是linux中的问题吗?我应该修改什么来防止死锁?
答案 0 :(得分:4)
unique_lock
无法锁定两次,如果要在两个线程上锁定互斥锁以便其中一个线程阻塞,则需要使用两个unique_lock
。
void Function00(long millisecond){
while (true){
{
std::unique_lock<std::mutex> lck(main_thread);
count1++;
printf("count0:%d count1:%d \n",count0,count1);
}
std::this_thread::sleep_for(std::chrono::milliseconds(millisecond));
}
}
void Function01(){
std::thread th(Function00, 1000);//count per 1 s
do{
{
std::unique_lock<std::mutex> lck(main_thread);
count0++;
}
std::this_thread::sleep_for(std::chrono::milliseconds(500));//count per 0.5 s
} while (1);
}