Skip to content

Commit b771ce7

Browse files
committed
Avoid race conditions when reading from serial
1 parent 244ca6b commit b771ce7

File tree

1 file changed

+23
-13
lines changed

1 file changed

+23
-13
lines changed

bufferflow_timed.go

+23-13
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ type BufferflowTimed struct {
1212
Port string
1313
Output chan []byte
1414
Input chan string
15+
done chan bool
1516
ticker *time.Ticker
1617
}
1718

@@ -23,22 +24,31 @@ func (b *BufferflowTimed) Init() {
2324
log.Println("Initting timed buffer flow (output once every 16ms)")
2425
bufferedOutput = ""
2526

26-
go func() {
27-
for data := range b.Input {
28-
bufferedOutput = bufferedOutput + data
29-
}
30-
}()
31-
3227
go func() {
3328
b.ticker = time.NewTicker(16 * time.Millisecond)
34-
for _ = range b.ticker.C {
35-
if bufferedOutput != "" {
36-
m := SpPortMessage{bufferedOutput}
37-
buf, _ := json.Marshal(m)
38-
b.Output <- []byte(buf)
39-
bufferedOutput = ""
29+
b.done = make(chan bool)
30+
Loop:
31+
for {
32+
select {
33+
case data := <-b.Input:
34+
bufferedOutput = bufferedOutput + data
35+
case <-b.ticker.C:
36+
if bufferedOutput != "" {
37+
m := SpPortMessage{bufferedOutput}
38+
buf, _ := json.Marshal(m)
39+
// data is now encoded in base64 format
40+
// need a decoder on the other side
41+
b.Output <- []byte(buf)
42+
bufferedOutput = ""
43+
}
44+
case <-b.done:
45+
break Loop
4046
}
4147
}
48+
49+
close(b.Input)
50+
close(b.done)
51+
4252
}()
4353

4454
}
@@ -97,5 +107,5 @@ func (b *BufferflowTimed) IsBufferGloballySendingBackIncomingData() bool {
97107

98108
func (b *BufferflowTimed) Close() {
99109
b.ticker.Stop()
100-
close(b.Input)
110+
b.done <- true
101111
}

0 commit comments

Comments
 (0)