-
Notifications
You must be signed in to change notification settings - Fork 0
/
MutexList.go
85 lines (72 loc) · 1.44 KB
/
MutexList.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
package lockfree
type myMutex interface {
lock()
unlock()
}
type mutexList struct {
nullVal interface{}
head *mutexItem
tail *mutexItem
disabled bool
elNum int64
mutex myMutex
}
type mutexItem struct {
next *mutexItem
valPtr ptr
}
// CreateMutexList 创建一个队列。
func CreateMutexList(defaultVal interface{}, spinlock bool) List {
list := &mutexList{
nullVal: defaultVal,
disabled: false,
elNum: 0,
}
if spinlock {
list.mutex = new(spinMutex)
} else {
list.mutex = new(mmutex)
}
// head和tail都初始化为同一个空节点,该节点不存实际元素。
sentinel := (&mutexItem{nil, nil})
list.head = sentinel
list.tail = sentinel
return list
}
func (list *mutexList) PushBack(val interface{}) bool {
if list.disabled {
return false
}
node := &mutexItem{
next: nil,
valPtr: ptr(&val),
}
list.mutex.lock()
list.tail.next = node
list.tail = node
list.mutex.unlock()
return true
}
func (list *mutexList) PopFront() (interface{}, bool) {
list.mutex.lock()
p := list.head
if p.next == nil {
list.mutex.unlock()
if list.disabled {
return list.nullVal, false
}
return list.nullVal, true
}
list.head = p.next
list.mutex.unlock()
return *((*interface{})(p.next.valPtr)), true
}
func (list *mutexList) Disable() {
list.disabled = true
}
func (list *mutexList) Enable() {
list.disabled = false
}
func (list *mutexList) IsEmpty() bool {
return list.head.next == nil
}