pthread-消费者/生产者模型实现
消费者/生产者模型是多线程编程开发的常用模型,该模型通过平衡生产者线程和消费者线程的工作能力来提高程序整体的数据处理能力。
设计该模型要注意以下几项:
- 资源池一般是有限的,访问资源是要加锁,访问完毕时记得解锁
- 生产者需要在资源池未满的情况下才能生产产品
- 消费者需要在资源池不空的情况下才能消费产品
- 设计时应考虑如何避免死锁问题
下面的例子是采用 semaphore,资源池为环形缓冲区,来实现消费者/生产者模型。代码如下:
#include <unistd.h>
#include <errno.h>
#include <pthread.h>
#include <semaphore.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#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) {