问题描述:
一组生产者进程和一组消费者进程共享一个初始为空、大小为 n 的缓冲区,只
有缓冲区没满时,生产者才能把消息放入到缓冲区,否则必须等待;只有缓冲区
不空时,消费者才能从中取出消息,否则必须等待。由于缓冲区是临界资源,它
只允许一个生产者放入消息,或者一个消费者从中取出消息。
分析:
- 关系分析:生产者和消费者对缓冲区互斥访问是互斥关系,同时生产者和
消费者又是一个相互协作的关系,只有生产者生产之后,消费者才能消费,
它们也是同步关系。 - 整理思路:这里比较简单,只有生产者和消费者两个进程,且这两个进程
存在着互斥关系和同步关系。那么需要解决的是互斥和同步的 PV 操作的
位置。3. 信号量设置:信号量 mutex 作为互斥信号量,用于控制互斥访问缓冲池,
初值为 1;信号量 full 用于记录当前缓冲池中“满”缓冲区数,初值为 0;
信号量 empty 用于记录当前缓冲池中“空”缓冲区数,初值为 n。
代码如下:
还是有点缺陷
如果编译失败,要额外加参数:-lpthread,例如:gcc -o p2 p2.c -lpthread
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <stdlib.h>
typedef int semaphore;
typedef int item;
#define Num 10
#define producerNum 10
#define consumerNum 10
item buffer[Num]={0};
int in=0, out=0;
int nextp=0, nextc=0;
semaphore mutex=1, empty=Num, full=0;
void *producer(void *a){
do {
/* code */
while (empty <= 0) {
/* code */
//printf("缓冲区已满\n");
}
empty--;
while(mutex <= 0);
mutex--;
nextp++;
printf("Producer--生产一个产品ID%d, 缓冲区位置为%d\n",nextp,in );
buffer[in]=nextp;
in=(in+1)%Num;
//proCount--;
mutex++;
full++;
sleep(100);
}while(1);
}
void *consumer(void *b){
do {
/* code */
while (full<=0) {
/* code */
//printf("缓冲区为空\n");
}
full--;
while(mutex <= 0 );
mutex--;
nextc=buffer[out];
printf("\t\t\tConsumer--消费一个产品ID%d, 缓冲区位置为%d\n",nextc,out );
out=(out+1)%Num;
mutex++;
empty++;
sleep(100);
} while(1);
}
int main(int argc, char const *argv[]) {
/* code */
//设置线程池
int all=producerNum+consumerNum;
pthread_t threadPool[all];
//生产者进程添加进入线程池
int i;
for(i=0; i < producerNum; i++){
pthread_t temp1;
if(pthread_create(&temp1,NULL,producer,NULL) == -1){
/* code */
printf("ERROR, fail to create producer%d\n", i);
exit(1);
}
threadPool[i]=temp1;
}
//消费者进程添加进入线程池
for(i=0; i < producerNum; i++){
pthread_t temp2;
if(pthread_create(&temp2,NULL,consumer,NULL) == -1){
/* code */
printf("ERROR, fail to create consumer%d\n", i);
exit(1);
}
threadPool[i+producerNum]=temp2;
}
//启动线程池
void *result;
for(i=0; i<all; i++){
if (pthread_join(threadPool[i],&result) == -1) {
/* code */
printf("ERROR\n");
exit(1);
}
}
return 0;
}