-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
81 lines (66 loc) · 1.69 KB
/
main.go
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
package main
import (
"fmt"
"math/rand"
"time"
"github.com/fatih/color"
)
// variables
var seatingCapacity = 15
var arrivalRate = 100
var cutDuration = 1000 * time.Millisecond
var timeOpen = 10 * time.Second
func main() {
// send our random number generator
rand.Seed(time.Now().UnixNano())
// print welcome message
color.Yellow("Welcome to the barber shop!")
color.Yellow("The sleeping barber problem")
color.Yellow("---------------------------")
// create channels if we need any
clientChan := make(chan string, seatingCapacity)
doneChan := make(chan bool)
// create the barbershop
shop := BarberShop{
ShopCapacity: seatingCapacity,
HairCutDuration: cutDuration,
NumberOfBarbers: 0,
ClientChan: clientChan,
BarberDoneChan: doneChan,
Open: true,
}
color.Green("The shop is open for the day!")
// add barbers (though problem ask for 1 barber only, you can add as much as you wish in this code)
shop.addBarber("Franklin")
//shop.addBarber("Trevor")
//shop.addBarber("Michael")
//shop.addBarber("CJ")
//shop.addBarber("Tommy")
//shop.addBarber("Lucy")
// start the barbershop as a goroutine
shopClosing := make(chan bool)
closed := make(chan bool)
go func() {
<-time.After(timeOpen)
shopClosing <- true
shop.closeShopForDay()
closed <- true
}()
// add clients
i := 1
go func() {
for {
// get a random number with average arrival rate
randomMilliseconds := rand.Int() % (2 * arrivalRate)
select {
case <-shopClosing:
return
case <-time.After(time.Millisecond * time.Duration(randomMilliseconds)):
shop.addClient(fmt.Sprintf("Client #%d", i))
i++
}
}
}()
// block until the barbershop is closed
<-closed
}