-
Notifications
You must be signed in to change notification settings - Fork 0
/
buffer.go
151 lines (118 loc) · 2.27 KB
/
buffer.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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
/**
* @file buffer.go
* @brief writer with buffer
* @author ligang
* @date 2016-02-04
*/
package golog
import (
"bufio"
"sync"
"time"
)
var bfr *bufFlushRoutine
var bfrInitMutex sync.Mutex
// must be called first
func InitBufferAutoFlushRoutine(maxBufNum int, timeInterval time.Duration) {
bfrInitMutex.Lock()
if bfr == nil {
bfr = &bufFlushRoutine{
buffers: make(map[uint64]*buffer),
bufAddCh: make(chan *buffer, maxBufNum),
bufDelCh: make(chan *buffer, maxBufNum),
freeCh: make(chan int),
}
go bfr.run(timeInterval)
}
bfrInitMutex.Unlock()
}
func FreeBuffers() {
bfr.freeCh <- 1
<-bfr.freeCh
bfr = nil
}
/**
* @name auto flush routine
* @{ */
type bufFlushRoutine struct {
curIndex uint64
buffers map[uint64]*buffer
bufAddCh chan *buffer
bufDelCh chan *buffer
freeCh chan int
}
func (this *bufFlushRoutine) addBuffer(buf *buffer) {
this.bufAddCh <- buf
}
func (this *bufFlushRoutine) delBuffer(buf *buffer) {
this.bufDelCh <- buf
}
func (this *bufFlushRoutine) flushAll() {
for index, buf := range this.buffers {
if buf == nil || buf.buf == nil {
delete(this.buffers, index)
} else {
buf.Flush()
}
}
}
func (this *bufFlushRoutine) run(timeInterval time.Duration) {
ticker := time.NewTicker(timeInterval)
for {
select {
case buf, _ := <-this.bufAddCh:
buf.index = this.curIndex
this.buffers[this.curIndex] = buf
this.curIndex++
case buf, _ := <-this.bufDelCh:
delete(this.buffers, buf.index)
buf.buf = nil
case <-ticker.C:
this.flushAll()
case <-this.freeCh:
this.flushAll()
this.freeCh <- 1
return
}
}
}
/** @} */
/**
* @name buffer
* @{ */
type buffer struct {
w IWriter
buf *bufio.Writer
lock *sync.Mutex
index uint64
}
func NewBuffer(w IWriter, bufsize int) *buffer {
this := &buffer{
w: w,
buf: bufio.NewWriterSize(w, bufsize),
lock: new(sync.Mutex),
}
bfr.addBuffer(this)
return this
}
func (this *buffer) Write(p []byte) (int, error) {
this.lock.Lock()
n, err := this.buf.Write(p)
this.lock.Unlock()
return n, err
}
func (this *buffer) Flush() error {
var err error
this.lock.Lock()
if this.buf != nil {
err = this.buf.Flush()
}
this.lock.Unlock()
return err
}
func (this *buffer) Free() {
this.Flush()
this.w.Free()
bfr.delBuffer(this)
}
/** @} */