Remove whitespace from wip test case
[eleutheria.git] / pthreads / sleepbarber.c
blob503703935f8cb4e766387ede6040df0d1e560b5d
1 /* compile with:
2 gcc sleepbarber.c -o sleepbarber -lpthread -Wall -W -Wextra -ansi -pedantic */
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <pthread.h>
7 #include <semaphore.h>
8 #include <unistd.h>
10 #define NUM_CUSTOMERS 10
11 #define MAX_FREESEATS 2
13 sem_t barsem;
14 sem_t cussem;
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);
25 int main(void)
27 pthread_t bartid;
28 pthread_t custid[NUM_CUSTOMERS];
29 int i;
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 :) */
46 diep("pthread_join");
48 return EXIT_SUCCESS;
51 void *barthread(void *arg)
53 while (1) {
54 printf("ZZZzzz\n");
55 sem_wait(&cussem);
56 sem_wait(&seasem);
57 freeseats++;
58 sem_post(&barsem);
59 sem_post(&seasem);
60 printf("The barber is cutting hair\n");
62 pthread_exit(NULL);
65 void *custhread(void *arg)
67 printf("Customer has arrived\n");
68 sem_wait(&seasem);
69 if (freeseats > 0) {
70 freeseats--;
71 sem_post(&cussem);
72 sem_post(&seasem);
73 sem_wait(&barsem);
75 else {
76 printf("No free seats - customer leaving\n");
77 sem_post(&seasem);
80 pthread_exit(NULL);
83 void diep(const char *s)
85 perror(s);
86 exit(EXIT_FAILURE);