concurrency: use channel to handle racing situation
This commit is contained in:
parent
cd4f6fc6c7
commit
d83f1c6f4c
@ -1,17 +1,31 @@
|
|||||||
package concurrency
|
package concurrency
|
||||||
|
|
||||||
import "time"
|
|
||||||
|
|
||||||
type WebsiteChecker func(string) bool
|
type WebsiteChecker func(string) bool
|
||||||
|
|
||||||
|
type result struct {
|
||||||
|
string
|
||||||
|
bool
|
||||||
|
}
|
||||||
|
|
||||||
func CheckWebsites(wc WebsiteChecker, urls []string) map[string]bool {
|
func CheckWebsites(wc WebsiteChecker, urls []string) map[string]bool {
|
||||||
results := make(map[string]bool)
|
results := make(map[string]bool)
|
||||||
|
resultChannel := make(chan result)
|
||||||
|
|
||||||
for _, url := range urls {
|
for _, url := range urls {
|
||||||
go func(u string) {
|
go func(u string) {
|
||||||
results[u] = wc(u)
|
resultChannel <- result{u, wc(u)}
|
||||||
}(url)
|
}(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
|
return results
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user