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
);
26 pthread_t custid
[NUM_CUSTOMERS
];
29 /* initialize the semaphores */
30 sem_init(&barsem
, 0, 0);
31 sem_init(&cussem
, 0, 0);
32 sem_init(&seasem
, 0, 1);
34 /* create the barber thread */
35 if (pthread_create(&bartid
, NULL
, barthread
, NULL
)) {
36 perror("pthread_create() error");
40 /* create the customer threads */
41 for (i
=0; i
<NUM_CUSTOMERS
; i
++) {
42 if (pthread_create(&custid
[i
], NULL
, custhread
, NULL
)) {
43 perror("pthread_create() error");
48 pthread_join(bartid
, NULL
); /* wait for the barber to retire :) */
52 void *barthread(void *arg
)
61 printf("The barber is cutting hair\n");
66 void *custhread(void *arg
)
68 printf("Customer has arrived\n");
77 printf("No free seats - customer leaving\n");