From d83f1c6f4c4f9e12dc3fe089b9e5f55c5ff54068 Mon Sep 17 00:00:00 2001 From: vinchent Date: Wed, 18 Sep 2024 09:48:00 +0200 Subject: [PATCH] concurrency: use channel to handle racing situation --- concurrency/concurrency.go | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/concurrency/concurrency.go b/concurrency/concurrency.go index e9e222a..a662e1d 100644 --- a/concurrency/concurrency.go +++ b/concurrency/concurrency.go @@ -1,17 +1,31 @@ package concurrency -import "time" - type WebsiteChecker func(string) bool +type result struct { + string + bool +} + func CheckWebsites(wc WebsiteChecker, urls []string) map[string]bool { results := make(map[string]bool) + resultChannel := make(chan result) for _, url := range urls { go func(u string) { - results[u] = wc(u) + resultChannel <- result{u, wc(u)} }(url) } - time.Sleep(2 * time.Second) + // XXX: it seems that this works on Go 1.23 + // for _, u := range urls { + // go func() { + // resultChannel <- result{u, wc(u)} + // }() + // } + for i := 0; i < len(urls); i++ { + r := <-resultChannel + results[r.string] = r.bool + } + return results }