-
Notifications
You must be signed in to change notification settings - Fork 0
/
ticket.go
110 lines (92 loc) · 1.81 KB
/
ticket.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
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
package main
import (
"log"
)
const QUEUE_CHUNK = 1024
var TICKETMASTER = NewTicketMaster(1)
type (
TicketRequest struct {
level Level
reply chan int
}
TicketMaster struct {
tickets uint // available tickets
returns chan int // channel to return tickets
request chan TicketRequest // channel to request tickets
maxLevel Level
// queued requests (by level)
queue map[Level][]chan int
}
)
func NewTicketMaster(tickets uint) *TicketMaster {
t := &TicketMaster{
tickets,
make(chan int),
make(chan TicketRequest),
0,
make(map[Level][]chan int),
}
go t.run()
return t
}
func (t *TicketMaster) getTicket(level Level) {
reply := make(chan int)
t.request <- TicketRequest{level, reply}
_ = <-reply
}
func (t *TicketMaster) returnTicket() {
t.returns <- 1
}
func (t *TicketMaster) run() {
for {
select {
case _ = <-t.returns:
if t.queueEmpty() {
t.tickets += 1
} else {
t.pop() <- 1
}
case r := <-t.request:
if t.tickets > 0 {
r.reply <- 1
t.tickets -= 1
} else {
t.push(r.reply, r.level)
}
}
}
}
func (t *TicketMaster) queueEmpty() bool {
return len(t.queue[t.maxLevel]) == 0
}
func (t *TicketMaster) pop() chan int {
q := t.queue[t.maxLevel]
var r chan int
t.queue[t.maxLevel], r = q[:len(q)-1], q[len(q)-1]
// Emptied the top queue?
if len(t.queue[t.maxLevel]) == 0 {
for {
t.maxLevel -= 1
if t.maxLevel < 0 || len(t.queue[t.maxLevel]) > 0 {
break
}
}
}
return r
}
func (t *TicketMaster) push(reply chan int, level Level) {
q, ok := t.queue[level]
if !ok {
q = make([]chan int, 0, QUEUE_CHUNK)
}
t.queue[level] = append(q, reply)
if level >= t.maxLevel {
t.maxLevel = level
}
log.Println("queue")
for k := range t.queue {
if len(t.queue[k]) > 0 {
log.Println(k, len(t.queue[k]))
}
}
}