-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
77 lines (64 loc) · 1.63 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
package main
import (
"fmt"
"math/rand"
"time"
)
var seatingCapacity = 10
var arrivalRate = 100
var cutDuration = 1000 * time.Millisecond
var timeOpen = 10 * time.Second
// go run -race .
func main() {
// Let's break this rather complex problem
// seed our random number generator
rand.New(rand.NewSource(time.Now().UnixNano()))
// print welcome message
fmt.Println("The Sleeping Barber Problem")
fmt.Println("---------------------------")
// create channels if we need any
clientChan := make(chan string, seatingCapacity)
doneChan := make(chan bool)
// create ds to represent the barbershop
shop := barberShop{
shopCapacity: seatingCapacity,
hairCutDuration: cutDuration,
numberOfBarbers: 0,
clientsChan: clientChan,
barbersDoneChan: doneChan,
open: true,
}
fmt.Println("The shop is open for the day!")
// add barbers
shop.addBarber("Fernando")
shop.addBarber("José")
// start the barbershop as a goroutine
shopClosing := make(chan bool)
closed := make(chan bool)
go func() {
// block until time open passes
// received value ignored
<-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
// this is the point when a client arrives at random intervals
case <-time.After(time.Millisecond * time.Duration(randomMilliseconds)):
shop.addClient(fmt.Sprintf("Client #%d", i))
i++
}
}
}()
// block until the barbershop is closed
<-closed
}