forked from open-falcon/falcon-plus
/
linkedlist.go
108 lines (86 loc) · 1.99 KB
/
linkedlist.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
package store
import (
"container/list"
"sync"
cmodel "github.com/open-falcon/falcon-plus/common/model"
)
type SafeLinkedList struct {
sync.RWMutex
Flag uint32
L *list.List
}
// 新创建SafeLinkedList容器
func NewSafeLinkedList() *SafeLinkedList {
return &SafeLinkedList{L: list.New()}
}
func (this *SafeLinkedList) PushFront(v interface{}) *list.Element {
this.Lock()
defer this.Unlock()
return this.L.PushFront(v)
}
func (this *SafeLinkedList) Front() *list.Element {
this.RLock()
defer this.RUnlock()
return this.L.Front()
}
func (this *SafeLinkedList) PopBack() *list.Element {
this.Lock()
defer this.Unlock()
back := this.L.Back()
if back != nil {
this.L.Remove(back)
}
return back
}
func (this *SafeLinkedList) Back() *list.Element {
this.Lock()
defer this.Unlock()
return this.L.Back()
}
func (this *SafeLinkedList) Len() int {
this.RLock()
defer this.RUnlock()
return this.L.Len()
}
// remain参数表示要给linkedlist中留几个元素
// 在cron中刷磁盘的时候要留一个,用于创建数据库索引
// 在程序退出的时候要一个不留的全部刷到磁盘
func (this *SafeLinkedList) PopAll() []*cmodel.GraphItem {
this.Lock()
defer this.Unlock()
size := this.L.Len()
if size <= 0 {
return []*cmodel.GraphItem{}
}
ret := make([]*cmodel.GraphItem, 0, size)
for i := 0; i < size; i++ {
item := this.L.Back()
ret = append(ret, item.Value.(*cmodel.GraphItem))
this.L.Remove(item)
}
return ret
}
//restore PushAll
func (this *SafeLinkedList) PushAll(items []*cmodel.GraphItem) {
this.Lock()
defer this.Unlock()
size := len(items)
if size > 0 {
for i := size - 1; i >= 0; i-- {
this.L.PushBack(items[i])
}
}
}
//return为倒叙的?
func (this *SafeLinkedList) FetchAll() ([]*cmodel.GraphItem, uint32) {
this.Lock()
defer this.Unlock()
count := this.L.Len()
ret := make([]*cmodel.GraphItem, 0, count)
p := this.L.Back()
for p != nil {
ret = append(ret, p.Value.(*cmodel.GraphItem))
p = p.Prev()
}
return ret, this.Flag
}