写了一个关于生产者消费者的程序,运行之后一直等待没有结果显示,求大神,哪里出错了?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
#define N 2 //生产者或消费者的数目
#define M 10 //缓冲区数目
int buffer[M]={0};
//int consumer_store[M];
int in=0; //逻辑指针,指向缓冲区中下一个空位,即生产者放置产品的地方
int out=0; //逻辑指针,指向缓冲区中第一个不为空的地方,即消费者消费的地方
sem_t empty; //同步信号量,表示缓冲区目前为空;
sem_t full; //同步信号量,表示缓冲区满;
pthread_mutex_t mutex; //互斥锁,两个线程不能同时访问缓冲区
//int count=0,num=0; //计数
int producer_num=0;
int consumer_num=0;
void print()
{
int i;
for(i=0;i<M;i++)
{
printf("%d ",buffer[i]);
}
printf("\n");
}
//生产者
void *producer()
{
int id=++producer_num;
// while(1)
// {
sleep(1);
sem_wait(&empty);
pthread_mutex_lock(&mutex);
printf("hhhhhhhhhhhhhhhhh\n");
printf("consumer %d in %d",id,in);
buffer[in]=1;
// num++;
print();
in=(in+1)%M;
// count++;
// ++producer_num;
pthread_mutex_unlock(&mutex);
sem_post(&full);
// }
}
//消费者
void *consumer()
{
int id=++consumer_num;
sleep(1);
sem_wait(&full);
pthread_mutex_lock(&mutex);
printf("ffffffffffffffffffffff\n");
printf("consumer %d in %d",id,out);
buffer[out]=0;
print();
out=(out+1)%M;
pthread_mutex_unlock(&mutex);
sem_post(&empty);
}
//输出
/*void print()
{
int i=0;
for(i=0;i<M;i++)
{
printf("the data of consumer:%c\n",consumer_store[i]);
}
}*/
int main()
{
pthread_t tid1[N];
pthread_t tid2[N];
int ret[N];
int k;
int sem1=sem_init(&empty,0,M); //初始化同步信号量
int sem2=sem_init(&empty,0,0);
if(sem1&&sem2!=0)
{
printf("sem init failed\n");
exit(1);
}
int mutex1=pthread_mutex_init(&mutex,NULL);//初始化互斥锁
if(mutex1!=0)
{
printf("mutex init failed\n");
exit(1);
}
//创建生产者线程
for(k=0;k<N;k++)
{
ret[k]=pthread_create(&tid1[k],NULL,producer,(void*)(&k));
if(ret[k]!=0)
{
fprintf(stderr,"create thread of producer failed.\n");
exit(1);
}
}
//创建消费者线程
for(k=0;k<N;k++)
{
ret[k]=pthread_create(&tid2[k],NULL,consumer,NULL);
if(ret[k]!=0)
{
fprintf(stderr,"create thread of consumer failed.\n");
exit(1);
}
}
for(k=0;k<N;k++)
{
pthread_join(tid1[k],NULL);
pthread_join(tid2[k],NULL);
}
exit(0);
}