Skip to content

Instantly share code, notes, and snippets.

@wangjohn
Last active January 9, 2025 17:55
Show Gist options
  • Select an option

  • Save wangjohn/a30ff7d0068535d576f7696616d5b92d to your computer and use it in GitHub Desktop.

Select an option

Save wangjohn/a30ff7d0068535d576f7696616d5b92d to your computer and use it in GitHub Desktop.
func ParallelSearch(query string) []SearchResult {
ctx, cancel := context.WithTimeout(context.Background(), 750*time.Millisecond)
defer cancel()
resultsChan := make(chan []SearchResult, len(backends))
var wg sync.WaitGroup
for _, backend := range backends {
wg.Add(1)
go func(backend func(string) ([]SearchResult, error)) {
defer wg.Done()
results, err := backend(query)
if err != nil {
return
}
select {
case resultsChan <- results:
case <-ctx.Done():
}
}(backend)
}
wg.Wait()
close(resultsChan)
var combined []SearchResult
for res := range resultsChan {
combined = append(combined, res...)
}
return combined
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment