-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathticket_allocator.go
73 lines (59 loc) · 1.6 KB
/
ticket_allocator.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
package flightorder
import "sync"
// TicketAllocator is responsible for ticket allocation.
type TicketAllocator interface {
AcquireTicket() *Ticket
ReleaseTicket(t *Ticket)
}
var (
_ TicketAllocator = (StdAllocator{})
_ TicketAllocator = (*SyncpoolAllocator)(nil)
_ TicketAllocator = (*testAllocator)(nil)
)
// StdAllocator is a standard ticket allocator without any memory reuse.
type StdAllocator struct{}
// AcquireTicket acquires a new ticket.
func (StdAllocator) AcquireTicket() *Ticket {
return newTicket()
}
// ReleaseTicket does nothing. Let GC erase ticket for us.
func (StdAllocator) ReleaseTicket(t *Ticket) { t.reset() }
// SyncpoolAllocator uses sync.Pool under the hood to reuse allocated tickets.
type SyncpoolAllocator struct {
pool *sync.Pool
}
// NewSyncpoolAllocator creates new SyncpoolAllocator.
func NewSyncpoolAllocator() *SyncpoolAllocator {
return &SyncpoolAllocator{
pool: &sync.Pool{
New: func() any {
return newTicket()
},
},
}
}
// AcquireTicket acquires a new ticket from the pool.
func (a *SyncpoolAllocator) AcquireTicket() *Ticket {
return a.pool.Get().(*Ticket)
}
// ReleaseTicket releases ticket to the pool.
func (a *SyncpoolAllocator) ReleaseTicket(t *Ticket) {
t.reset()
a.pool.Put(t)
}
// testAllocator is a test allocator.
type testAllocator struct {
released []*Ticket
mux sync.Mutex
}
func newTestAllocator() *testAllocator {
return &testAllocator{}
}
func (a *testAllocator) AcquireTicket() *Ticket {
return newTicket()
}
func (a *testAllocator) ReleaseTicket(t *Ticket) {
a.mux.Lock()
defer a.mux.Unlock()
a.released = append(a.released, t)
}