Skip to content

Commit 567c865

Browse files
committed
refactor: replace mutex with atomic boolean for thread-safe isClosing flag
1 parent 33d9e31 commit 567c865

File tree

1 file changed

+4
-10
lines changed

1 file changed

+4
-10
lines changed

Diff for: serialport.go

+4-10
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ import (
2020
"encoding/base64"
2121
"io"
2222
"strconv"
23-
"sync"
23+
"sync/atomic"
2424
"time"
2525
"unicode/utf8"
2626

@@ -44,9 +44,7 @@ type serport struct {
4444

4545
// Keep track of whether we're being actively closed
4646
// just so we don't show scary error messages
47-
isClosing bool
48-
49-
mu sync.Mutex
47+
isClosing atomic.Bool
5048

5149
isClosingDueToError bool
5250

@@ -87,15 +85,13 @@ func (p *serport) reader(buftype string) {
8785
n, err := p.portIo.Read(serialBuffer)
8886
bufferPart := serialBuffer[:n]
8987

90-
p.mu.Lock()
9188
//if we detect that port is closing, break out of this for{} loop.
92-
if p.isClosing {
89+
if p.isClosing.Load() {
9390
strmsg := "Shutting down reader on " + p.portConf.Name
9491
log.Println(strmsg)
9592
h.broadcastSys <- []byte(strmsg)
9693
break
9794
}
98-
p.mu.Unlock()
9995

10096
// read can return legitimate bytes as well as an error
10197
// so process the n bytes red, if n > 0
@@ -353,9 +349,7 @@ func spHandlerOpen(portname string, baud int, buftype string) {
353349
}
354350

355351
func (p *serport) Close() {
356-
p.mu.Lock()
357-
p.isClosing = true
358-
p.mu.Unlock()
352+
p.isClosing.Store(true)
359353

360354
p.bufferwatcher.Close()
361355
p.portIo.Close()

0 commit comments

Comments
 (0)