Last active
September 25, 2021 06:53
-
-
Save ciscorn/d5710883aaa31f488e692faee4047ca1 to your computer and use it in GitHub Desktop.
A Tour of Go: Exercise: Web Crawler without Mutex (https://tour.golang.org/concurrency/10)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
) | |
type Fetcher interface { | |
Fetch(url string) (body string, urls []string, err error) | |
} | |
func main() { | |
cache := make(map[string]bool) | |
ch_queue := make(chan string, 10) | |
ch_result := make(chan string, 10) | |
num_running := 0 | |
ch_queue <- "https://golang.org/" | |
for { | |
select { | |
case url := <-ch_queue: | |
if _, ok := cache[url]; !ok { | |
cache[url] = true | |
num_running += 1 | |
go func(url string) { | |
body, urls, err := fetcher.Fetch(url) | |
if err == nil { | |
for _, u := range urls { | |
ch_queue <- u | |
} | |
ch_result <- fmt.Sprintf("found: %s %q\n", url, body) | |
} else { | |
ch_result <- fmt.Sprintln(err) | |
} | |
}(url) | |
} | |
case res := <-ch_result: | |
num_running -= 1 | |
fmt.Println(res) | |
} | |
if num_running == 0 && len(ch_result) == 0 && len(ch_queue) == 0 { | |
return | |
} | |
} | |
} | |
type fakeFetcher map[string]*fakeResult | |
type fakeResult struct { | |
body string | |
urls []string | |
} | |
func (f fakeFetcher) Fetch(url string) (string, []string, error) { | |
if res, ok := f[url]; ok { | |
return res.body, res.urls, nil | |
} | |
return "", nil, fmt.Errorf("not found: %s", url) | |
} | |
var fetcher = fakeFetcher{ | |
"https://golang.org/": &fakeResult{ | |
"The Go Programming Language", | |
[]string{ | |
"https://golang.org/pkg/", | |
"https://golang.org/cmd/", | |
}, | |
}, | |
"https://golang.org/pkg/": &fakeResult{ | |
"Packages", | |
[]string{ | |
"https://golang.org/", | |
"https://golang.org/cmd/", | |
"https://golang.org/pkg/fmt/", | |
"https://golang.org/pkg/os/", | |
}, | |
}, | |
"https://golang.org/pkg/fmt/": &fakeResult{ | |
"Package fmt", | |
[]string{ | |
"https://golang.org/", | |
"https://golang.org/pkg/", | |
}, | |
}, | |
"https://golang.org/pkg/os/": &fakeResult{ | |
"Package os", | |
[]string{ | |
"https://golang.org/", | |
"https://golang.org/pkg/", | |
}, | |
}, | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment