您的位置:首页 > 编程语言 > C语言/C++

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

2017-09-30 16:28 239 查看
// 前面一篇博客的生产者-消费者的例子是基于链表的,其空间可以动态分配,现在基于固定大小的环形队列重写这个程序:
#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重写本节的程序。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c语言 semaphore 链表
相关文章推荐