C++实现简单生产者消费者模型

      消费者/生产者模型是多线程编程开发的常用模型,该模型通过平衡生产者线程和消费者线程的工作能力来提高程序整体的数据处理能力。

       一般来说,我们的资源池是有限的,访问资源需要加锁,访问完以后需要解锁,生产者需要在资源池未满的情况下才能生产产品,消费者需要在资源池不空的情况下才能消费产品。且在设计时需要注意死锁问题。

       下面采用semaphore,资源池为环形缓冲区,来实现生产者消费者模型:    

#include 
#include 
#include 
#include 
#include 

#include 
#include 
#include 

#define ERROR(func, no) { \
        fprintf(stderr, "%s: %s\n", func, strerror(no)); \
        exit(EXIT_FAILURE); \
    }

#define DEFAULT_CONSUMER_CNT    1
#define DEFAULT_PRODUCER_CNT    3
#define DEFAULT_BUFFER_SIZE 10

static size_t in; //  producer's current pos
static size_t out; // consumer's current pos
static size_t consumer_id; // current product id for consumer 
static size_t producer_id; // current product id for producer
static size_t consumer_cnt; // count of consumers
static size_t producer_cnt; // count of producers
static size_t buff_size; // resource buffer size

static int* g_buffer = NULL; // pointer to resource buffer
static pthread_t* g_thread = NULL; // pointer to thread IDs

static pthread_mutex_t g_mutex; //mutex
static sem_t* g_sem_empty_ptr = NULL; // semaphore for consumer
static sem_t* g_sem_full_ptr = NULL; // semaphore for producer

void* consume(void* arg) {
    int id = *(int*)arg;
    free(arg);

    while(1) {
        printf("Consumer[%d] waits buffer not empty\n", id);
        sem_wait(g_sem_empty_ptr);
        pthread_mutex_lock(&g_mutex);

        int i, flag;
        for(i=0; i

       

你可能感兴趣的:(C++,C/C++/C#开发实战365)