-
Notifications
You must be signed in to change notification settings - Fork 5.9k
Expand file tree
/
Copy pathseat_lock_manager.go
More file actions
76 lines (64 loc) · 1.4 KB
/
seat_lock_manager.go
File metadata and controls
76 lines (64 loc) · 1.4 KB
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
package concertbookingsystem
import (
"container/heap"
"sync"
"time"
)
type SeatLockInfo struct {
Seat *Seat
ExpiryTime time.Time
index int
}
type SeatLockMinHeap []*SeatLockInfo
func (h SeatLockMinHeap) Len() int { return len(h) }
func (h SeatLockMinHeap) Less(i, j int) bool { return (h)[i].ExpiryTime.Before((h)[j].ExpiryTime) }
func (h SeatLockMinHeap) Swap(i, j int) {
(h)[i], (h)[j] = (h)[j], (h)[i]
(h)[i].index = i
(h)[j].index = j
}
func (h *SeatLockMinHeap) Push(x interface{}) {
n := len(*h)
item := x.(*SeatLockInfo)
item.index = n
*h = append(*h, item)
}
func (h *SeatLockMinHeap) Pop() interface{} {
prev := *h
n := len(prev)
item := prev[n-1]
item.index = -1
*h = prev[0 : n-1]
return item
}
type SeatLockManager struct {
heap SeatLockMinHeap
mu sync.Mutex
}
func NewSeatLockManager() *SeatLockManager {
return &SeatLockManager{
heap: make(SeatLockMinHeap, 0),
}
}
func (slm *SeatLockManager) AddSeatLock(seat *Seat, duration time.Duration) {
slm.mu.Lock()
defer slm.mu.Unlock()
lockInfo := &SeatLockInfo{
Seat: seat,
ExpiryTime: time.Now().Add(duration),
}
heap.Push(&slm.heap, lockInfo)
}
func (slm *SeatLockManager) ReleaseExpiredLocks() {
slm.mu.Lock()
defer slm.mu.Unlock()
now := time.Now()
for slm.heap.Len() > 0 {
lockInfo := slm.heap[0]
if lockInfo.ExpiryTime.After(now) {
break
}
heap.Pop(&slm.heap)
lockInfo.Seat.Release()
}
}