forked from smarty-prototypes/go-disruptor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreader.go
64 lines (56 loc) · 1.41 KB
/
reader.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
package disruptor
import (
"runtime"
"time"
)
type Reader struct {
read *Cursor
written *Cursor
upstream Barrier
consumer Consumer
ready bool
}
func NewReader(read, written *Cursor, upstream Barrier, consumer Consumer) *Reader {
return &Reader{
read: read,
written: written,
upstream: upstream,
consumer: consumer,
ready: false,
}
}
func (this *Reader) Start() {
this.ready = true
go this.receive()
}
func (this *Reader) Stop() {
this.ready = false
}
func (this *Reader) receive() {
previous := this.read.Load()
idling, gating := 0, 0
for {
lower := previous + 1
upper := this.upstream.Read(lower)
if lower <= upper {
this.consumer.Consume(lower, upper)
this.read.Store(upper)
previous = upper
} else if upper = this.written.Load(); lower <= upper {
time.Sleep(time.Microsecond)
// Gating--TODO: wait strategy (provide gating count to wait strategy for phased backoff)
gating++
idling = 0
} else if this.ready {
time.Sleep(time.Millisecond)
// Idling--TODO: wait strategy (provide idling count to wait strategy for phased backoff)
idling++
gating = 0
} else {
break
}
// sleeping increases the batch size which reduces number of writes required to store the sequence
// reducing the number of writes allows the CPU to optimize the pipeline without prediction failures
runtime.Gosched() // LockSupport.parkNanos(1L); http://bit.ly/1xiDINZ
}
}