-
Notifications
You must be signed in to change notification settings - Fork 0
/
slist.go
70 lines (61 loc) · 1.09 KB
/
slist.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
package gorqs
import (
"sync"
"sync/atomic"
)
// node is an element of a synchronized singly linked list (slist).
type node struct {
job jobber
next *node
}
// slist represents a synchronized (concurent safe) singly linked-list.
type slist struct {
mu *sync.Mutex
head *node
count atomic.Int64
}
// list provides a synchronized singly linked list to be used as internal job queue.
func list() *slist {
return &slist{
mu: &sync.Mutex{},
head: nil,
}
}
// isEmpty tells
func (sl *slist) isEmpty() bool {
return sl.count.Load() == 0
}
// push adds a job to the queue.
func (sl *slist) push(j jobber) {
sl.mu.Lock()
node := &node{
job: j,
next: nil,
}
if sl.head == nil {
sl.head = node
sl.count.Add(1)
sl.mu.Unlock()
return
}
n := sl.head
for n.next != nil {
n = n.next
}
n.next = node
sl.count.Add(1)
sl.mu.Unlock()
}
// pop returns the oldest job from the queue.
func (sl *slist) pop() jobber {
sl.mu.Lock()
if sl.head == nil {
sl.mu.Unlock()
return nil
}
head := sl.head
sl.head = sl.head.next
sl.count.Add(-1)
sl.mu.Unlock()
return head.job
}