#include <stdio.h>
#include <stdlib.h>
#include"unistd.h"
//#ifndef "unistd.h" #define "unistd.h" #include <io.h> #include <process.h>#endif /* _UNISTD_H */
//#include"pthread.h"
#include"semaphore.h"
#include"fcntl.h"
#include "errno.h"
#define N 5
//引入3个信号量:mutex,customers,barbers;
sem_t mutex,customers,barber;
int waiting =0;
int chair [5];
void *barbers();
void *customer();
int main(int argc,char *argv[])
//定义10个信号量和一个理发师信号量
pthread_t Customer_id[10],Barbers_id;
int i;
sem_init(&mutex,0,1); //init mutex semaphore to 1
sem_init (&barber,0,1);
sem_init(&customers,0,0);
//init semaphore customers to 0
//creat barber pthread
void *barber()
{int i;
int next;
//wait(customers),如果没有顾客,理发师休息
sem_wait(&customers)
sem_wait (&mutex)
//wait(mutex)
waiting--;
//the number of waiting reduce one
for(i=0,i<5;i++)
{for (i=0;i<5;i++)
pthread_creat(&Barber_id,null,(void)*barber null);
for (i=0,i<10,i++)
pthread_creat(&Customer_id[],null,(void)*customer,(void)*(i+1) );
for (i=0,i<10,i++)
pthread_join(&Barber_id[i],null);
for (i=0,i<5;i++)
{pthread_join(&Barber_id,null);
return 0;}
if (char[i]!=0)
{next=chair[i];
chair[i]=0
break;
}
printf("理发师正在为第%d顾客理发\n",next);
sleep(3);
sem_post(&mutex);
sem_post(&barber);
}
//creat customer pthread
void *customer(void *arg)
{int i;
sem_wait(&mutex);
//等待(&mutex)if(等待人数<n)
if (waiting<n)
{
waiting++;//等待数加1
for(i=0,i<5;i++)
{
if chair[i]==0}
{
chair[i]=(int)arg;
break;
}
}
printf("*************************\n");
printf("进入:数字是%d 顾客进来,坐在%的椅子\n",(int)arg,(i+1));
printf("这有%d个顾客在等待椅上\n",waiting);
printf("顾客位置是 :");
for (i=0,i<5;i++)
printf("%d ,char[i]");
printf("\n");
sleep(1);
sem_post(&mutex);
//释放signal(mutex)
sem_post(&customers);
//signal(customers)
sem_post(&barber);
//signal(barber)
}
else
{
printf("数字是%d 进来,没有椅子坐,顾客%d号离开\n"(int)arg,(int)arg);
sem_post(&mutex);}}
目前暂无任何回答
- 0 回答
- 0 关注
- 1134 浏览
添加回答
举报
0/150
提交
取消