#include<stdio.h>#include<stdlib.h>#include<time.h>#include<sys/types.h>#include<pthread.h>#include<semaphore.h>#include<string.h>#include<unistd.h>//semaphoressem_t mutex,barbers,customers;int waiting;structdata{int id;};//理发师void*Barbers(void* param){while(1){int id =((structdata*)param)->id;sem_wait(&customers);sem_wait(&mutex);
waiting--;printf(" waiting-1:------%d\n",waiting);sem_post(&mutex);sem_post(&barbers);printf("BARBERS-CUT\n");printf(" waiting\n");sleep(5);// pthread_exit(0);}}//顾客void*Customers(void* param){int id =((structdata*)param)->id;sem_wait(&mutex);if(waiting<10){
waiting++;printf(" waiting+1:------%d\n",waiting);sem_post(&mutex);sem_post(&customers);sem_wait(&barbers);printf("%d CUSTOMERS-CUT\n",id);}elseprintf("FULL\n");sem_post(&mutex);// pthread_exit(0);}intmain(){//pthreadpthread_t tid;// the thread identifierpthread_attr_t attr;//set of thread attributes/* get the default attributes */pthread_attr_init(&attr);//initial the semaphoressem_init(&mutex,0,1);sem_init(&customers,0,0);sem_init(&barbers,0,0);
waiting =0;int id =0;while(scanf("%d",&id)!=EOF){char role;//producer or consumerscanf("%c",&role);structdata* d =(structdata*)malloc(sizeof(structdata));
d->id = id;if(role =='B'){printf(" BARBER\n");pthread_create(&tid,&attr, Barbers, d);}elseif(role =='C'){printf(" %d CUSTOMER\n",id);pthread_create(&tid,&attr, Customers, d);}}//信号量销毁sem_destroy(&mutex);sem_destroy(&barbers);sem_destroy(&customers);return0;}/*
1 C
2 B
3 C
4 C
*/