From b771ce7b8e87068b13ae6df26b516440e0c876c3 Mon Sep 17 00:00:00 2001 From: Matteo Suppo Date: Wed, 12 Oct 2016 15:03:39 +0200 Subject: [PATCH] Avoid race conditions when reading from serial --- bufferflow_timed.go | 36 +++++++++++++++++++++++------------- 1 file changed, 23 insertions(+), 13 deletions(-) diff --git a/bufferflow_timed.go b/bufferflow_timed.go index 3ce3b6a85..ee2e92063 100644 --- a/bufferflow_timed.go +++ b/bufferflow_timed.go @@ -12,6 +12,7 @@ type BufferflowTimed struct { Port string Output chan []byte Input chan string + done chan bool ticker *time.Ticker } @@ -23,22 +24,31 @@ func (b *BufferflowTimed) Init() { log.Println("Initting timed buffer flow (output once every 16ms)") bufferedOutput = "" - go func() { - for data := range b.Input { - bufferedOutput = bufferedOutput + data - } - }() - go func() { b.ticker = time.NewTicker(16 * time.Millisecond) - for _ = range b.ticker.C { - if bufferedOutput != "" { - m := SpPortMessage{bufferedOutput} - buf, _ := json.Marshal(m) - b.Output <- []byte(buf) - bufferedOutput = "" + b.done = make(chan bool) + Loop: + for { + select { + case data := <-b.Input: + bufferedOutput = bufferedOutput + data + case <-b.ticker.C: + if bufferedOutput != "" { + m := SpPortMessage{bufferedOutput} + buf, _ := json.Marshal(m) + // data is now encoded in base64 format + // need a decoder on the other side + b.Output <- []byte(buf) + bufferedOutput = "" + } + case <-b.done: + break Loop } } + + close(b.Input) + close(b.done) + }() } @@ -97,5 +107,5 @@ func (b *BufferflowTimed) IsBufferGloballySendingBackIncomingData() bool { func (b *BufferflowTimed) Close() { b.ticker.Stop() - close(b.Input) + b.done <- true }