From 092178ff741d80bb32b5bd290ff1c567fc671ef0 Mon Sep 17 00:00:00 2001 From: Cristian Maglie Date: Thu, 14 Mar 2024 10:57:51 +0100 Subject: [PATCH] Fixed extremely rare race condition in DiscoveryManager --- .../discovery/discoverymanager/discoverymanager.go | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/internal/arduino/discovery/discoverymanager/discoverymanager.go b/internal/arduino/discovery/discoverymanager/discoverymanager.go index 2651e9b524f..74504c48062 100644 --- a/internal/arduino/discovery/discoverymanager/discoverymanager.go +++ b/internal/arduino/discovery/discoverymanager/discoverymanager.go @@ -171,9 +171,17 @@ func (dm *DiscoveryManager) Watch() (*PortWatcher, error) { defer dm.watchersMutex.Unlock() delete(dm.watchers, watcher) close(watcher.feed) + watcher.feed = nil } go func() { dm.watchersMutex.Lock() + defer dm.watchersMutex.Unlock() + + // Check if the watcher is still alive (it could have been closed before the goroutine started...) + if watcher.feed == nil { + return + } + // When a watcher is started, send all the current active ports first... for _, cache := range dm.watchersCache { for _, ev := range cache { @@ -182,7 +190,6 @@ func (dm *DiscoveryManager) Watch() (*PortWatcher, error) { } // ...and after that add the watcher to the list of watchers receiving events dm.watchers[watcher] = true - dm.watchersMutex.Unlock() }() return watcher, nil }