生产者 - 消费者问题

时间:2013-04-21 20:37:51

标签: c++ linux pthreads producer-consumer

您好我正在尝试编写一个解决生产者 - 消费者问题的算法,而且我遇到了障碍。这是我从代码中获得的输出:

制作:6 6 0 0 0 0 0 0 0 0 0 END

然后程序退出。我不确定我哪里出错了?我在创建循环缓冲区时做错了吗?

#include <iostream>
#include <pthread.h>
#include <semaphore.h>
#include <pthread.h>
#include <stdlib.h> 
#include <stdio.h>
#include <string>
#include <fstream>
using namespace std;

#define BUFFER_SIZE 10

void *produce(void *);
void *consume(void *);
int produceItem(void);
void insertItem(int item);
void removeItem(void);
void printBuffer(void);

int head = 0;
int tail = 0;
int item;
int bufferCount = 0;
pthread_t producer, consumer;
pthread_cond_t Buffer_Not_Full=PTHREAD_COND_INITIALIZER;
pthread_cond_t Buffer_Not_Empty=PTHREAD_COND_INITIALIZER;
pthread_mutex_t lock;
sem_t sem_filledSlots;
sem_t sem_emptySlots;
int buffer[BUFFER_SIZE];


int main() {

    int emptyCount;
    int item;
    srand (time(NULL));


    sem_init(&sem_filledSlots, 0, 0);
    sem_init(&sem_emptySlots, 0, BUFFER_SIZE);

    sem_getvalue(&sem_emptySlots, &emptyCount);


    pthread_create (&producer, NULL, &produce, NULL);
    pthread_create (&consumer, NULL, &consume, NULL);


    return 0;
}

void *produce(void *)
{

    for(int i = 0; i <15; i++)
    {
        item = produceItem();
        sem_wait(&sem_emptySlots);
        pthread_mutex_lock(&lock);
        printf("Producing: %d \n", item);
        buffer[head] = item;
        head = (head + 1) % BUFFER_SIZE;
        printBuffer();
        pthread_mutex_unlock(&lock);
        sem_post(&sem_filledSlots);
    }
}

void *consume(void *)
{
    for(int i = 0; i <15; i++)
    {
        sem_wait(&sem_filledSlots);
        pthread_mutex_lock(&lock);
        printf("Consuming %d \n", buffer[tail]); 
        buffer[tail] = 0;
        tail = (tail + 1) % BUFFER_SIZE;
        bufferCount--;
        printBuffer();
        pthread_mutex_unlock(&lock); 
        sem_post(&sem_emptySlots);
    }
}

int produceItem(void)
{

    int x = (rand()%11 + 1);
    return x;
}

void printBuffer(void)
{

    for(int i = 0; i <BUFFER_SIZE; i++)
    {

        printf("%d ", buffer[i]);

    }
    printf("END \n");
}

1 个答案:

答案 0 :(得分:0)

退出程序前你缺少pthread_join:

....     在pthread_join(生产商,NULL);     在pthread_join(消费者,NULL);     返回0; ....