Dummy commit to test new ssh key
[eleutheria.git] / pthreads / sleepbarber.c
blobe809b9a4411950d96d1e059d2738c57385d040de
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);
24 int main(void)
26 pthread_t bartid;
27 pthread_t custid[NUM_CUSTOMERS];
28 int i;
30 /* Initialize the semaphores */
31 sem_init(&barsem, 0, 0);
32 sem_init(&cussem, 0, 0);
33 sem_init(&seasem, 0, 1);
35 /* Create the barber thread */
36 if (pthread_create(&bartid, NULL, barthread, NULL))
37 diep("pthread_create");
39 /* Create the customer threads */
40 for (i = 0; i < NUM_CUSTOMERS; i++)
41 if (pthread_create(&custid[i], NULL, custhread, NULL))
42 diep("pthread_create");
44 if (pthread_join(bartid, NULL)) /* wait for the barber to retire :) */
45 diep("pthread_join");
47 return EXIT_SUCCESS;
50 void *barthread(void *arg)
52 for (;;) {
53 printf("ZZZzzz\n");
54 sem_wait(&cussem);
55 sem_wait(&seasem);
56 freeseats++;
57 sem_post(&barsem);
58 sem_post(&seasem);
59 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);