基于信号量实现多线程生产者消费者模型。
编程思路:
1.食物的初始化编号为100: beginnum = 100;
2.仓库有5个空碗,最多保存5个食物:queue[5];
3.初始化空碗的数量为5,食物的数量为0:
sem_init(&sem_bowl,0,5);
sem_init(&sem_food,0,0);
4.创建生产者和消费者线程;
5.生产者通过sem_wait(&sem_bowl)函数监控空碗的数量;
6.消费者通过sem_wait(&sem_food)函数监控食物的数量;
7.由于最开始阶段空碗的数量是5,生产者线程会先执行。先通过sem_wait(&sem_bowl)函数将空碗数量减一,然后向这个碗中放入一个食物;
8.生产者每生产一个食物,会将食物的数量加一:sem_post(&sem_food);
9.系统监控到食物的数量大于0的时候,会随机唤醒一个等待的消费者线程;
10.消费者线程首先会通过sem_wait(&sem_food)函数将食物的数量减一,然后取走食物;
11.消费者线程每取走一个食物,通过sem_post(&sem_bowl)函数将空碗的数量加一;
12.由于空碗的数量最多为5,仓库里最多只能保存5个食物,sem_food信号量最大值只能到5。
代码:
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
#include <string.h>
#include <stdlib.h>
int beginnum = 100;
int queue[5];
sem_t sem_bowl, sem_food;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void * product_handle(void * arg) {
int i = 0;
while(1) {
sem_wait(&sem_bowl);
printf(“%s number %d\n”,FUNCTION,beginnum);
queue[(i++)%5] = beginnum++;
//printf(“%s number %d\n”,FUNCTION,beginnum);
sem_post(&sem_food);
sleep(rand()%1);
}
return NULL;
}
int i =0;
void * customer_handle(void * arg) {
while(1) {
// pthread_mutex_lock(&mutex);
sem_wait(&sem_food);
int num = queue[(i++)%5];
printf(“%ld customer number %d\n”,pthread_self(),num);
sem_post(&sem_bowl);
// pthread_mutex_unlock(&mutex);
sleep(rand()%3);
}
return NULL;
}
int main()
{
sem_init(&sem_bowl,0,5);
sem_init(&sem_food,0,0);
pthread_t pdit_product,pdit_customer[5];
pthread_create(&pdit_product,NULL,product_handle,NULL);
pthread_create(&pdit_customer[0],NULL,customer_handle,NULL);
pthread_create(&pdit_customer[1],NULL,customer_handle,NULL);
pthread_join(pdit_product,NULL);
pthread_join(pdit_customer[0],NULL);
pthread_join(pdit_customer[1],NULL);
sem_destroy(&sem_bowl);
sem_destroy(&sem_food);
pthread_mutex_destroy(&mutex);
return 0;
}