c++ - 生产者-消费者问题

标签 c++ linux pthreads producer-consumer

嗨,我正在尝试编写一种算法来解决生产者-消费者问题,但遇到了障碍。这是我从代码中得到的输出:

制作:6 6 0 0 0 0 0 0 0 0 0 结束

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

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

最佳答案

退出程序之前缺少 pthread_join:

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

关于c++ - 生产者-消费者问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16135958/

相关文章:

c++ - 获取 Windows 错误代码的标识符

c++ - pthread_cancel 没有取消线程——C++

c - POSIX 线程和信号量

linux - Pthread 线程和信号

linux - awk 如何提取其他字段 "if duplicates in fields"仅当先前字段相同且大于零时

c - 我使用 pthread 创建了一个矩阵乘法程序但是 [0][0] block 值总是 0

c++ - 如何转换boost::fusion::vector的类型?

c++ - Windows 上的 DLL Main 对比。 __attribute__((constructor)) Linux 上的入口点

c - 在这种情况下使用错误

linux - Ubuntu - 批量文件重命名