Someone_R 2021-12-02 17:28 采纳率: 0%
浏览 10
已结题

(生产者消费者问题)C++11<mutex>和<thread>的使用 多线程 出现死锁

问题遇到的现象和发生背景

一个生产者消费者模型,在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

我的解答思路和尝试过的方法
我想要达到的结果
  • 写回答

0条回答 默认 最新

    报告相同问题?

    问题事件

    • 系统已结题 12月10日
    • 创建了问题 12月2日

    悬赏问题

    • ¥20 WPF MVVM模式 handycontrol 框架, hc:SearchBar 控件 Text="{Binding NavMenusKeyWords}" 绑定取不到值
    • ¥15 需要手写数字信号处理Dsp三个简单题 不用太复杂
    • ¥15 数字信号处理考试111
    • ¥100 关于#audobe audition#的问题,如何解决?
    • ¥15 allegro17.2生成bom表是空白的
    • ¥15 请问一下怎么打通CAN通讯
    • ¥20 如何在 rocky9.4 部署 CDH6.3.2?
    • ¥35 navicat将excel中的数据导入mysql出错
    • ¥15 rt-thread线程切换的问题
    • ¥15 高通uboot 打印ubi init err 22