Skip to content

Commit 265f8c7

Browse files
committed
fix(sync-server): use mutex to avoid race conditions on goroutines
1 parent f2aa0f8 commit 265f8c7

File tree

1 file changed

+8
-0
lines changed

1 file changed

+8
-0
lines changed

internal/tui/sync_server.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,14 @@ import (
77
"net"
88
"strconv"
99
"strings"
10+
"sync"
1011
)
1112

1213
type SyncServer struct {
1314
listener net.Listener
1415
port int
1516
clients map[net.Conn]bool
17+
clientsMu sync.Mutex
1618
running bool
1719
currentSlide int
1820
}
@@ -59,10 +61,12 @@ func (s *SyncServer) Stop() {
5961
s.listener.Close()
6062
}
6163

64+
s.clientsMu.Lock()
6265
for client := range s.clients {
6366
client.Close()
6467
}
6568
s.clients = make(map[net.Conn]bool)
69+
s.clientsMu.Unlock()
6670

6771
slog.Info("Sync server stopped")
6872
}
@@ -72,13 +76,15 @@ func (s *SyncServer) BroadcastSlideChange(slideNumber int) {
7276

7377
message := fmt.Sprintf("SLIDE:%d\n", slideNumber)
7478

79+
s.clientsMu.Lock()
7580
for client := range s.clients {
7681
_, err := client.Write([]byte(message))
7782
if err != nil {
7883
delete(s.clients, client)
7984
client.Close()
8085
}
8186
}
87+
s.clientsMu.Unlock()
8288
}
8389

8490
func (s *SyncServer) acceptConnections() error {
@@ -94,7 +100,9 @@ func (s *SyncServer) acceptConnections() error {
94100
return fmt.Errorf("failed to accept connection: %w", err)
95101
}
96102

103+
s.clientsMu.Lock()
97104
s.clients[conn] = true
105+
s.clientsMu.Unlock()
98106

99107
currentSlide := s.currentSlide
100108

0 commit comments

Comments
 (0)