karmada-search: Fix lock race affects watch RestChan not close, causing client watch api to hang

Signed-off-by: xigang <wangxiang2014@gmail.com>
This commit is contained in:
xigang 2023-11-08 12:12:20 +08:00
parent 1b2c6edfba
commit 9c9c52cb2e
1 changed files with 15 additions and 15 deletions

View File

@ -195,9 +195,21 @@ func (w *watchMux) AddSource(watcher watch.Interface, decorator func(watch.Event
// Start run the watcher // Start run the watcher
func (w *watchMux) Start() { func (w *watchMux) Start() {
for _, source := range w.sources { wg := sync.WaitGroup{}
go w.startWatchSource(source.watcher, source.decorator) for i := range w.sources {
source := w.sources[i]
wg.Add(1)
go func() {
defer wg.Done()
w.startWatchSource(source.watcher, source.decorator)
}()
} }
go func() {
// close result chan after all goroutines exit, avoiding data race.
defer close(w.result)
wg.Wait()
}()
} }
// ResultChan implements watch.Interface // ResultChan implements watch.Interface
@ -220,7 +232,6 @@ func (w *watchMux) Stop() {
case <-w.done: case <-w.done:
default: default:
close(w.done) close(w.done)
close(w.result)
} }
} }
@ -246,19 +257,8 @@ func (w *watchMux) startWatchSource(source watch.Interface, decorator func(watch
select { select {
case <-w.done: case <-w.done:
return return
default: case w.result <- copyEvent:
} }
func() {
w.lock.RLock()
defer w.lock.RUnlock()
select {
case <-w.done:
return
default:
w.result <- copyEvent
}
}()
} }
} }