-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQ.17.cpp
More file actions
78 lines (68 loc) · 1.75 KB
/
Q.17.cpp
File metadata and controls
78 lines (68 loc) · 1.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<pthread.h>
#include<errno.h>
#include<sys/types.h>
#include<semaphore.h>
#define N 5
time_t end_time;/*end time*/
sem_t mutex,customers,barbers;/*Three semaphors*/
int count=0;/*The number of customers waiting for haircuts*/
void barber(void *arg);
void customer(void *arg);
int main(int argc,char *argv[])
{
pthread_t id1,id2;
int status=0;
end_time=time(NULL)+20;/*Barber Shop Hours is 20s*/
/*Semaphore initialization*/
sem_init(&mutex,0,1);
sem_init(&customers,0,0);
sem_init(&barbers,0,1);
/*Barber_thread initialization*/
status=pthread_create(&id1,NULL,(void *)barber,NULL);
if(status!=0)
perror("create barbers is failure!\n");
/*Customer_thread initialization*/
status=pthread_create(&id2,NULL,(void *)customer,NULL);
if(status!=0)
perror("create customers is failure!\n");
/*Customer_thread first blocked*/
pthread_join(id2,NULL);
pthread_join(id1,NULL);
exit(0);
}
void barber(void *arg)/*Barber Process*/
{
while(time(NULL)<end_time || count>0)
{
sem_wait(&customers);/*P(customers)*/
sem_wait(&mutex);/*P(mutex)*/
count--;
printf("Barber:cut hair,count is:%d.\n",count);
sem_post(&mutex);/*V(mutex)*/
sem_post(&barbers);/*V(barbers)*/
sleep(3);
}
}
void customer(void *arg)/*Customers Process*/
{
while(time(NULL)<end_time)
{
sem_wait(&mutex);/*P(mutex)*/
if(count<N)
{
count++;
printf("Customer:add count,count is:%d\n",count);
sem_post(&mutex);/*V(mutex)*/
sem_post(&customer);/*V(customers)*/
sem_wait(&barbers);/*P(barbers)*/
}
else
/*V(mutex)*/
/*If the number is full of customers,just put the mutex lock let go*/
sem_post(&mutex);
sleep(1);
}
}