-
Notifications
You must be signed in to change notification settings - Fork 0
/
barber.cpp
130 lines (119 loc) · 2.39 KB
/
barber.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <semaphore.h>
#include <iostream>
#include <random>
#include <time.h>
using std::cout;
using std::endl;
sem_t bin_sem;
sem_t mutex, sofa, empty, full, payment, receipt;
int count=0;
int sofas=0;
int customer_thread=10;
int finished = 0;
void *customer(void *arg)
{
sleep(rand()%10);
cout << "new customer:" << pthread_self() << endl;
sem_wait(&mutex);
if(count > sofas)
{
cout << pthread_self() << ":too many customer, leave" << endl;
finished++;
sem_post(&mutex);
}
else
{
count += 1;
sem_post(&mutex);
if(count > 1)
{
cout << pthread_self() << ":waiting sofa" << endl;
sem_wait(&sofa);
cout << pthread_self() << ":get sofa" << endl;
sem_wait(&empty);
cout << pthread_self() << ":leave from sofa" << endl;
sem_post(&sofa);
}
else
{
sem_wait(&empty);
}
sem_post(&full);
cout << pthread_self() << ":sit in haircut chair" << endl;
sem_post(&payment);
sem_wait(&receipt);
cout << pthread_self() << ":finished haircut" << endl;
sem_post(&empty);
sem_wait(&mutex);
count--;
sem_post(&mutex);
cout << pthread_self() << ":done, leaving!" << endl;
}
}
void *barber(void *arg)
{
while(true)
{
sleep(1);
sem_wait(&full);
cout << "begin haircut" << endl;
sem_wait(&payment);
cout << "get money" << endl;
sem_post(&receipt);
sem_wait(&mutex);
finished++;
sem_post(&mutex);
cout << "finished:" << finished << endl;
if(customer_thread == finished)
{
exit(0);
}
}
}
int main()
{
sofas=7;
cout << "input sofa number:";
std::cin >> sofas;
cout << "customer number:";
std::cin >> customer_thread ;
int res;
res = sem_init(&mutex, 0, 1);
res |= sem_init(&empty, 0, 1);
res |= sem_init(&full, 0, 0);
res |= sem_init(&payment, 0, 0);
res |= sem_init(&receipt, 0, 1);
res |= sem_init(&sofa, 0, sofas);
if (res != 0)
{
perror("Semaphore initialization failed");
exit(1);
}
printf("semaphore inited\n");
pthread_t a_thread;
res = pthread_create(&a_thread, NULL, barber, NULL);
if (res != 0)
{
perror("baber thread creation failure");
}
printf("barber thread created\n");
srand((unsigned)time(NULL));
for(int i = 0; i < customer_thread; i++)
{
res = pthread_create(&a_thread, NULL, customer, NULL);
if (res != 0)
{
perror("customer thread creation failure");
exit(2);
}
}
while (1)
{
sleep(1);
}
}