forked from simoneguidi94/gopapageno
/
stackptrpool.go
50 lines (44 loc) · 942 Bytes
/
stackptrpool.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
package regex
import (
"fmt"
"sync"
)
/*
stackPtrPool allows to preallocate elements with type stackPtr.
It is thread-safe.
*/
type stackPtrPool struct {
pool []stackPtr
cur int
lock sync.Mutex
}
/*
newStackPtrPool creates a new pool, allocating memory for a number of elements equal to length.
*/
func newStackPtrPool(length int) *stackPtrPool {
p := stackPtrPool{make([]stackPtr, length), 0, sync.Mutex{}}
return &p
}
/*
GetSync gets an item from the pool if available, otherwise it initializes a new one.
It is thread-safe.
*/
func (p *stackPtrPool) GetSync() *stackPtr {
p.lock.Lock()
if p.cur >= len(p.pool) {
fmt.Println("Allocating a new stack!")
newStack := new(stackPtr)
p.lock.Unlock()
return newStack
}
addr := &p.pool[p.cur]
p.cur++
p.lock.Unlock()
return addr
}
/*
Remainder returns the number of items remaining in the pool.
*/
func (p *stackPtrPool) Remainder() int {
return len(p.pool) - p.cur
}