c用信号量(Semaphore)实现消费者生产者同步

// 前面一篇博客的生产者-消费者的例子是基于链表的,其空间可以动态分配,现在基于固定大小的环形队列重写这个程序:
#include <stdlib.h>
#include <pthread.h>
#include <stdio.h>
#include <semaphore.h>

#define NUM 5
int queue[NUM];
/**
 * semaphore变量的类型为sem_t,sem_init()初始化一个semaphore变量,
 * value参数表示可用资源的数量,pshared参数为0表示信号量用于同一进程的线程间同步
 */
sem_t blank_number, product_number;
void *producer(void *arg)
{
    static int p = 0;
    while(1){
        // 调用sem_wait()可以获得资源,使semaphore的值减1,如果调用sem_wait()时semaphore的值已经是0,则挂起等待。
        // 如果不希望挂起等待,可以调用sem_trywait()。
        // 这里使得blank_number的值减1,初始值是5
        sem_wait(&blank_number);
        queue[p] = rand()%1000;
        printf("Produce %d\n", queue[p]);
        p = (p+1)%NUM;
        sleep(rand()%5);
        // 调用sem_post()可以释放资源,使semaphore的值加1,同时唤醒挂起等待的线程。
        // 使得product_number值加1,初始值是0
        sem_post(&product_number);
    }
}

void *consumer(void *arg)
{
    static int c = 0;
    while(1){
        // 使得product_number值加1,初始值是0
        sem_wait(&product_number);
        printf("Consume %d\n", queue[c]);
        c = (c+1)%NUM;
        sleep(rand()%5);
        // 这里使得blank_number的值减1,初始值是5
        sem_post(&blank_number);
    }
}

int main(int argc, char *argv[])
{
    //刷新 console cdt下的配置,其他可以忽略
    setbuf(stdout,NULL);
    pthread_t pid, cid;

    sem_init(&blank_number, 0, NUM);
    sem_init(&product_number, 0, 0);
    pthread_create(&pid, NULL, producer, NULL);
    pthread_create(&cid, NULL, consumer, NULL);
    pthread_join(pid, NULL);
    pthread_join(cid, NULL);
    sem_destroy(&blank_number);
    sem_destroy(&product_number);
    return 0;
}

这篇和上一篇博客的例子给出一个重要的提示:用Condition Variable可以实现Semaphore。有时间用Condition Variable实现Semaphore,然后用自己实现的Semaphore重写本节的程序。

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值