Skip to content

Commit

Permalink
fix: add mutex for thread-safe access in serialport isClosing
Browse files Browse the repository at this point in the history
  • Loading branch information
dido18 committed Jan 16, 2025
1 parent 67db428 commit ad598e5
Showing 1 changed file with 8 additions and 0 deletions.
8 changes: 8 additions & 0 deletions serialport.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import (
"encoding/base64"
"io"
"strconv"
"sync"
"time"
"unicode/utf8"

Expand All @@ -45,6 +46,8 @@ type serport struct {
// just so we don't show scary error messages
isClosing bool

mu sync.Mutex

isClosingDueToError bool

// buffered channel containing up to 25600 outbound messages.
Expand Down Expand Up @@ -84,13 +87,15 @@ func (p *serport) reader(buftype string) {
n, err := p.portIo.Read(serialBuffer)
bufferPart := serialBuffer[:n]

p.mu.Lock()
//if we detect that port is closing, break out of this for{} loop.
if p.isClosing {
strmsg := "Shutting down reader on " + p.portConf.Name
log.Println(strmsg)
h.broadcastSys <- []byte(strmsg)
break
}
p.mu.Unlock()

// read can return legitimate bytes as well as an error
// so process the n bytes red, if n > 0
Expand Down Expand Up @@ -348,7 +353,10 @@ func spHandlerOpen(portname string, baud int, buftype string) {
}

func (p *serport) Close() {
p.mu.Lock()
p.isClosing = true
p.mu.Unlock()

p.bufferwatcher.Close()
p.portIo.Close()
serialPorts.MarkPortAsClosed(p.portName)
Expand Down

0 comments on commit ad598e5

Please sign in to comment.