2 gcc sleepbarber.c -o sleepbarber -lpthread -Wall -W -Wextra -ansi -pedantic */
10 #define NUM_CUSTOMERS 10
11 #define MAX_FREESEATS 2
15 sem_t seasem
; /* mutual exclusion for 'freeseats' */
17 unsigned int freeseats
= MAX_FREESEATS
;
19 /* function prototypes */
20 void *barthread(void *arg
);
21 void *custhread(void *arg
);
22 void diep(const char *s
);
28 pthread_t custid
[NUM_CUSTOMERS
];
31 /* initialize the semaphores */
32 sem_init(&barsem
, 0, 0);
33 sem_init(&cussem
, 0, 0);
34 sem_init(&seasem
, 0, 1);
36 /* create the barber thread */
37 if (pthread_create(&bartid
, NULL
, barthread
, NULL
))
38 diep("pthread_create");
40 /* create the customer threads */
41 for (i
= 0; i
< NUM_CUSTOMERS
; i
++)
42 if (pthread_create(&custid
[i
], NULL
, custhread
, NULL
))
43 diep("pthread_create");
45 if (pthread_join(bartid
, NULL
)) /* wait for the barber to retire :) */
51 void *barthread(void *arg
)
60 printf("The barber is cutting hair\n");
65 void *custhread(void *arg
)
67 printf("Customer has arrived\n");
76 printf("No free seats - customer leaving\n");
83 void diep(const char *s
)