-
Notifications
You must be signed in to change notification settings - Fork 21
/
queue_test.go
115 lines (97 loc) · 2.06 KB
/
queue_test.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
109
110
111
112
113
114
115
// Copyright 2020 The golang.design Initiative authors.
// All rights reserved. Use of this source code is governed
// by a MIT license that can be found in the LICENSE file.
package lockfree_test
import (
"fmt"
"math/rand"
"sync"
"sync/atomic"
"testing"
"golang.design/x/lockfree"
)
func TestQueueDequeueEmpty(t *testing.T) {
q := lockfree.NewQueue()
if q.Dequeue() != nil {
t.Fatalf("dequeue empty queue returns non-nil")
}
}
func TestQueue_Length(t *testing.T) {
q := lockfree.NewQueue()
if q.Length() != 0 {
t.Fatalf("empty queue has non-zero length")
}
q.Enqueue(1)
if q.Length() != 1 {
t.Fatalf("count of enqueue wrong, want %d, got %d.", 1, q.Length())
}
q.Dequeue()
if q.Length() != 0 {
t.Fatalf("count of dequeue wrong, want %d, got %d", 0, q.Length())
}
}
func ExampleQueue() {
q := lockfree.NewQueue()
q.Enqueue("1st item")
q.Enqueue("2nd item")
q.Enqueue("3rd item")
fmt.Println(q.Dequeue())
fmt.Println(q.Dequeue())
fmt.Println(q.Dequeue())
// Output:
// 1st item
// 2nd item
// 3rd item
}
type queueInterface interface {
Enqueue(interface{})
Dequeue() interface{}
}
type mutexQueue struct {
v []interface{}
mu sync.Mutex
}
func newMutexQueue() *mutexQueue {
return &mutexQueue{v: make([]interface{}, 0)}
}
func (q *mutexQueue) Enqueue(v interface{}) {
q.mu.Lock()
q.v = append(q.v, v)
q.mu.Unlock()
}
func (q *mutexQueue) Dequeue() interface{} {
q.mu.Lock()
if len(q.v) == 0 {
q.mu.Unlock()
return nil
}
v := q.v[0]
q.v = q.v[1:]
q.mu.Unlock()
return v
}
func BenchmarkQueue(b *testing.B) {
length := 1 << 12
inputs := make([]int, length)
for i := 0; i < length; i++ {
inputs = append(inputs, rand.Int())
}
q, mq := lockfree.NewQueue(), newMutexQueue()
b.ResetTimer()
for _, q := range [...]queueInterface{q, mq} {
b.Run(fmt.Sprintf("%T", q), func(b *testing.B) {
var c int64
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
i := int(atomic.AddInt64(&c, 1)-1) % length
v := inputs[i]
if v >= 0 {
q.Enqueue(v)
} else {
q.Dequeue()
}
}
})
})
}
}