Cosmetic changes
[eleutheria.git] / pthreads / sleepbarber.c
blob720f4d1b95001884988d0ce4641e148c51218c0d
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <pthread.h>
4 #include <semaphore.h>
5 #include <unistd.h>
7 #define NUM_CUSTOMERS 10
8 #define MAX_FREESEATS 2
10 sem_t barsem;
11 sem_t cussem;
12 sem_t seasem; /* mutual exclusion for 'freeseats' */
14 unsigned int freeseats = MAX_FREESEATS;
16 /* function prototypes */
17 void *barthread(void *arg);
18 void *custhread(void *arg);
20 int main() {
21 pthread_t bartid;
22 pthread_t custid[NUM_CUSTOMERS];
23 int i;
25 /* initialize the semaphores */
26 sem_init(&barsem, 0, 0);
27 sem_init(&cussem, 0, 0);
28 sem_init(&seasem, 0, 1);
30 /* create the barber thread */
31 if (pthread_create(&bartid, NULL, barthread, NULL)) {
32 perror("pthread_create() error");
33 exit(EXIT_FAILURE);
36 /* create the customer threads */
37 for (i=0; i<NUM_CUSTOMERS; i++) {
38 if (pthread_create(&custid[i], NULL, custhread, NULL)) {
39 perror("pthread_create() error");
40 exit(EXIT_FAILURE);
44 pthread_join(bartid, NULL); /* wait for the barber to retire :) */
45 return EXIT_SUCCESS;
48 void *barthread(void *arg) {
49 while (1) {
50 printf("ZZZzzz\n");
51 sem_wait(&cussem);
52 sem_wait(&seasem);
53 freeseats++;
54 sem_post(&barsem);
55 sem_post(&seasem);
56 printf("The barber is cutting hair\n");
58 pthread_exit(NULL);
61 void *custhread(void *arg) {
62 printf("Customer has arrived\n");
63 sem_wait(&seasem);
64 if (freeseats > 0) {
65 freeseats--;
66 sem_post(&cussem);
67 sem_post(&seasem);
68 sem_wait(&barsem);
70 else {
71 printf("No free seats - customer leaving\n");
72 sem_post(&seasem);
75 pthread_exit(NULL);