使用多个使用者线程时崩溃

crashed when using multiple consumer thread

本文关键字:线程 崩溃 使用者      更新时间:2023-10-16

只有一个消费者工作正常,但多个消费者会崩溃,我想知道为什么。

#include <iostream>
#include <string>
#include <vector>
#include <pthread.h>
#include <unistd.h>
#include <queue>
using namespace std;

pthread_mutex_t g_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t g_qs_notempty = PTHREAD_COND_INITIALIZER;
pthread_cond_t g_qs_notfull = PTHREAD_COND_INITIALIZER;
queue<string> qs;
void *
producer(void *arg)
{
    static vector<string> vs{"a ","b ","c ","d ","e "};
    static int idx = 0;
    while(1){
        pthread_mutex_lock(&g_mutex);
        if(qs.size()==5)//full
            pthread_cond_wait(&g_qs_notfull,&g_mutex);
        qs.push(vs[idx]);
        idx = (idx+1)%5;
        pthread_cond_signal(&g_qs_notempty);
        pthread_mutex_unlock(&g_mutex);
    }
    return NULL;
}
void *
consumer(void *arg)
{
    while(1){
        pthread_mutex_lock(&g_mutex);
        if(qs.empty())
            pthread_cond_wait(&g_qs_notempty,&g_mutex);
        cout<<qs.front();
        qs.pop();
        pthread_cond_signal(&g_qs_notfull);
        pthread_mutex_unlock(&g_mutex);
    }
    return NULL;
}

int main()
{
    struct thread_info *tinfo;
    pthread_attr_t attr;
    pthread_t thread_id;
    pthread_attr_init(&attr);
    pthread_create(&thread_id, &attr, &producer, 0);
    pthread_create(&thread_id, &attr, &consumer, 0);
    pthread_create(&thread_id, &attr, &consumer, 0); //adding this line will crash
    pthread_exit(0);
}

不能保证_signal()只唤醒一个线程。

所以你必须在醒来后重新检查你的情况。修复代码的一个简单方法是将if切换为while