简体   繁体   English

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

[英]crashed when using multiple consumer thread

Only one consumer works fine, but multiple consumers will crash, I am wondering why.只有一个消费者工作正常,但多个消费者会崩溃,我想知道为什么。

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

It is not guaranteed that _signal() wakes up only a single thread. 不能保证_signal()只唤醒一个线程。

So you must recheck your condition upon wakeup.因此,您必须在醒来时重新检查您的状况。 A simply way to fix your code is to switch the if for while .修复代码的一个简单方法是切换if for while

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM