pthread-消费者/生产者模型实现

本文介绍了使用pthread库在多线程编程中实现消费者/生产者模型,强调了资源池管理、线程同步和避免死锁的关键点。示例代码采用环形缓冲区和semaphore,展示了在Mac和Ubuntu上的运行差异。
摘要由CSDN通过智能技术生成

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) {
        
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值