问题遇到的现象和发生背景
一个生产者消费者模型,在linux下运行,只是用C++11的 mutex和thread这两库的 api 替换了 linux 的 pthread.h 的 api
可能是多线程对调用一个公共函数,并加互斥锁,产生了死锁,但是逻辑上感觉没错,因为只是替换了api,原程序可以正常跑。
但是终止了 原因产生死锁
而且只用了一个锁,怎么会产生死锁呢,最多是饥饿吧。
问题相关代码,请勿粘贴截图
#include<iostream>
#include<string.h>
// #include<pthread.h>
#include<unistd.h>
#include<thread>
#include<mutex>
#include<condition_variable>
#include<vector>
using namespace std;
int cur = 0;
int buf[10];
int in = 0, out = 0;
int items = 0, space = 10;
static mutex mtx;
static unique_lock<mutex>lk1(mtx);
static condition_variable empty;
static condition_variable full;
int current = 0; // producer运行加1,consumer运行减1
bool flag; // 标记线程结束运行
void producer(void){
lk1.lock();
while(!space){
full.wait(lk1);
}
buf[in] = current++;
in = (in + 1)%10;
items++;
space--;
// printf( "producer %zu , current = %d\n", pthread_self(), current );
for( int i = 0; i < 10; i++ ) {
printf( "%-4d", buf[i] );
}
printf( "\n\n" );
empty.notify_one();
lk1.unlock();
// pthread_exit(NULL);
}
void consumer(void){
lk1.lock();
while(!items){
empty.wait(lk1);
}
buf[out] = current++;
out = (out + 1)%10;
items--;
space++;
// printf( "producer %zu , current = %d\n", pthread_self(), current );
for( int i = 0; i < 10; i++ ) {
printf( "%-4d", buf[i] );
}
printf( "\n\n" );
full.notify_one();
lk1.unlock();
// pthread_exit(NULL);
}
int main(){
// pthread_t pro[5], con[5];
// thread pro[5], con[5];
vector<thread> obj1;
vector<thread> obj2;
for(int i = 0; i < 5; i++){
obj1.emplace_back(thread(producer));
obj2.emplace_back(thread(consumer));
// pthread_create(&pro[i], NULL, producer, NULL);
// pthread_create(&con[i], NULL, consumer, NULL);
}
sleep(1); // 让线程运行一秒
flag = false;
// for(int i = 0; i < 5; i++) {
// pthread_join( pro[i], NULL );
// pthread_join( con[i], NULL );
// }
for(int i = 0; i < 5; i++){
obj1[i].join();
obj2[i].join();
}
return 0;
}
运行结果及报错内容
❯ ./test
terminate called after throwing an instance of 'std::system_error'
what(): Resource deadlock avoided
[1] 5746 abort ./test