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

时间:2014-04-20 19:00:54

标签: c++ multithreading pthreads

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

#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);
}

1 个答案:

答案 0 :(得分:1)

It is not guaranteed that _signal() wakes up only a single thread.

所以你必须在醒来后重新检查你的病情。修复代码的一种简单方法是切换if的{​​{1}}。