/
heap_atomic.go
74 lines (64 loc) · 1.06 KB
/
heap_atomic.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
package heap_atomic
import (
"runtime"
"sync/atomic"
"github.com/johnsiilver/golib/queue/fifo/unbounded/internal/spin"
)
// Unbounded indicates that the Queue should have no memory bounds.
const Unbounded = -1
const (
unlocked = int32(0)
locked = int32(1)
)
type queue struct {
v interface{}
next *queue
}
type Buffer struct {
ptr *queue
last *queue
lockInt int32
}
func (b *Buffer) Force(item interface{}) {
b.lock()
if b.ptr == nil {
q := queue{v: item}
b.ptr = &q
b.last = &q
} else {
q := queue{v: item}
b.last.next = &q
b.last = &q
}
b.unlock()
}
func (b *Buffer) Pull() interface{} {
sleeper := spin.Sleeper{}
for {
b.lock()
if b.ptr != nil {
v := b.ptr.v
b.ptr = b.ptr.next
b.unlock()
return v
}
b.unlock()
sleeper.Sleep()
}
}
func (b *Buffer) lock() {
for {
if atomic.CompareAndSwapInt32(&b.lockInt, unlocked, locked) {
return
}
runtime.Gosched()
}
}
func (b *Buffer) unlock() {
for {
if atomic.CompareAndSwapInt32(&b.lockInt, locked, unlocked) {
return
}
runtime.Gosched()
}
}