一共有三个生产者和四个消费者,缓冲区大小为10,为了简单起见,生产者生产的都是5这个常数,但是不知道为什么运行不了,Linux下我也不知道该怎么调试,代码是这样的:
//生产者消费者问题
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<semaphore.h>
int in=0, out=0; //in和out为生产者和消费者在缓冲区内使用的数组下标
int buffer[10]={0,0,0,0,0,0,0,0,0,0}; //缓冲区大小为10
sem_t mutex,empty,full; //mutex为缓冲池的互斥信号量,empty表示空缓冲区的数量,full表示满缓冲区数量
int produce_an_item(){ //提供给生产者
int i=5;
return i;
}
//生产者
void *producter(void *arg){
while(1){
int i=produce_an_item(); //得到数据
sem_wait(&empty);
sem_wait(&mutex);
printf("生产者读到了数据%d\n",i);
buffer[in]=i; //将数据放入缓冲区
in = (in+1)%10; //下标向前移动
sem_post(&mutex);
sem_post(&full);
}
}
//消费者
void *consumer(void *arg){
while(1){
sem_wait(&full);
sem_wait(&mutex);
int i=buffer[out]; //i代表从缓冲区读出的数据
printf("消费者取出的数据为:%d\n",i);
buffer[out]=0; //读取后将此置为0
out=(out+1)%10;
sem_post(&mutex);
sem_post(&empty);
}
}
int main(){
//创建生产者线程
pthread_t p1,p2,p3;
pthread_create(&p1,NULL,producter,NULL);
pthread_create(&p2,NULL,producter,NULL);
pthread_create(&p3,NULL,producter,NULL);
//创建消费者进程
pthread_t c1,c2,c3,c4;
pthread_create(&c1,NULL,consumer,NULL);
pthread_create(&c2,NULL,consumer,NULL);
pthread_create(&c3,NULL,consumer,NULL);
pthread_create(&c4,NULL,consumer,NULL);
//初始化互斥信号量
sem_init(&mutex,0,1);
sem_init(&empty,0,10);
sem_init(&full,0,0);
//运行线程
pthread_join(p1,NULL);
pthread_join(p2,NULL);
pthread_join(p3,NULL);
pthread_join(c1,NULL);
pthread_join(c2,NULL);
pthread_join(c3,NULL);
pthread_join(c4,NULL);
return 0;
}
程序经常运行不起来,不知道是为什么,头都晕了。。请大家帮忙看看