Cosmetic changes
[eleutheria.git] / pthreads / sleepbarber.c
blob5f2a61c81a0d1a892f7c4c03451cfe7b4421d02f
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);
23 int main(void)
25 pthread_t bartid;
26 pthread_t custid[NUM_CUSTOMERS];
27 int i;
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");
37 exit(EXIT_FAILURE);
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");
44 exit(EXIT_FAILURE);
48 pthread_join(bartid, NULL); /* wait for the barber to retire :) */
49 return EXIT_SUCCESS;
52 void *barthread(void *arg)
54 while (1) {
55 printf("ZZZzzz\n");
56 sem_wait(&cussem);
57 sem_wait(&seasem);
58 freeseats++;
59 sem_post(&barsem);
60 sem_post(&seasem);
61 printf("The barber is cutting hair\n");
63 pthread_exit(NULL);
66 void *custhread(void *arg)
68 printf("Customer has arrived\n");
69 sem_wait(&seasem);
70 if (freeseats > 0) {
71 freeseats--;
72 sem_post(&cussem);
73 sem_post(&seasem);
74 sem_wait(&barsem);
76 else {
77 printf("No free seats - customer leaving\n");
78 sem_post(&seasem);
81 pthread_exit(NULL);