操作系统课程设计-生产者消费者问题linux

#include
#include
#define MAX 30
#define BUFFER_SIZE 20
pthread_mutex_t the_mutex,the_main,the_p;
pthread_cond_t condc,condp;
int buffer[BUFFER_SIZE];
int in=0;
int out=0;
int counter=0;
int flg[30]={0};
int k=0;
int p=0;
void *producer1(void* s)
{
pthread_mutex_lock(&the_main);

pthread_mutex_unlock(&the_main);

int proid=(int)s;

int i;

for(i=1;i<=MAX;i++)

{

pthread_mutex_lock(&the_mutex);

while(counter==BUFFER_SIZE)

{
printf("%d号生产者 wait...\n",proid);
pthread_cond_wait(&condp,&the_mutex);
printf("%d号生产者 唤醒...\n",proid);}

buffer[in]=1;


printf("%d号生产者生产1放入%d中\n",proid,in);

in=(in+1)%BUFFER_SIZE;
counter++;
pthread_cond_signal(&condc);
pthread_mutex_unlock(&the_mutex);
}
pthread_mutex_lock(&the_p);
p++;
printf("%d号生产者线程结束\n",proid);
pthread_mutex_unlock(&the_p);

return 0;
}

void *consumer1(void* s)
{
pthread_mutex_lock(&the_main);
pthread_mutex_unlock(&the_main);
int conid=(int)s;
int j=1;
int k=0;
while(1)
{
pthread_mutex_lock(&the_mutex);
if(p==30&&counter==0){pthread_mutex_unlock(&the_mutex);break;}
// printf("p=%d counter=%d\n",p,counter);
while(counter==0){if(p==30&&counter==0){pthread_mutex_unlock(&the_mutex);break;}printf("%d号消费者wait...\n",conid); pthread_cond_wait(&condc,&the_mutex);printf("%d号消费者唤醒...\n",conid);}
if(buffer[out]==4)
{
printf("%d号消费者在%d处消费%d counter=%d p=%d\n",conid,out);
buffer[out]=0;
out=(out+1)%BUFFER_SIZE;
counter--;
pthread_cond_signal(&condp);
}
if(buffer[out]==1&&flg[conid]==0)
{
flg[conid]=1;
printf("%d号消费者在%d处消费%d counter=%d p=%d\n",conid,out);
for(j=1;j<=29;j=j+2)
if(flg[j]==1)
k++;
if(k==15)
{
k=0;
for(j=1;j<=29;j++)
flg[j]=0;
buffer[out]=0;
out=(out+1)%BUFFER_SIZE;
counter--;
pthread_cond_signal(&condp);
}else
k=0;
}
else
{pthread_cond_signal(&condc);}
pthread_mutex_unlock(&the_mutex);
}
printf("%d消费者线程结束\n",conid);
pthread_exit(0);

}

int main(int argc,char **argv)
{
int j;
pthread_t pro[31],con[31];
pthread_mutex_init(&the_mutex,0);
pthread_mutex_init(&the_main,0);
pthread_cond_init(&condc,0);
pthread_cond_init(&condp,0);
pthread_mutex_lock(&the_main);
for(j=1;j<=10;j=j+2)
{
pthread_create(&pro[j],0,producer1,(void*)j);
pthread_create(&con[j],0,consumer1,(void*)j);
}

printf("线程创建完成\n");
pthread_mutex_unlock(&the_main);
for(j=1;j<=30;j++)
{
pthread_join(con[j],

0);
}
printf("消费者线程结束\n");
pthread_mutex_destroy(&the_main);
pthread_cond_destroy(&condc);
pthread_cond_destroy(&condp);
pthread_mutex_destroy(&the_mutex);
}


相关文档
最新文档