Skip to content

Commit ad598e5

Browse files
committed
fix: add mutex for thread-safe access in serialport isClosing
1 parent 67db428 commit ad598e5

File tree

1 file changed

+8
-0
lines changed

1 file changed

+8
-0
lines changed

serialport.go

+8
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import (
2020
"encoding/base64"
2121
"io"
2222
"strconv"
23+
"sync"
2324
"time"
2425
"unicode/utf8"
2526

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

49+
mu sync.Mutex
50+
4851
isClosingDueToError bool
4952

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

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

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

350355
func (p *serport) Close() {
356+
p.mu.Lock()
351357
p.isClosing = true
358+
p.mu.Unlock()
359+
352360
p.bufferwatcher.Close()
353361
p.portIo.Close()
354362
serialPorts.MarkPortAsClosed(p.portName)

0 commit comments

Comments
 (0)