练习地址: Go指南
关键代码段:
注意 wg.Done 的位置不能放到 Crawl 方法中 sc.wg.Add(1) 后面,否则会出问题。【参考链接中的规则一】
Unlock同理
type SafeCounter struct {
mp map[string]bool
mux sync.Mutex
wg sync.WaitGroup
}
// Crawl 使用 fetcher 从某个 URL 开始递归的爬取页面,直到达到最大深度。
func (sc *SafeCounter)Crawl(url string, depth int, fetcher Fetcher) {
defer sc.wg.Done()
sc.mux.Lock()
sc.mp[url] = true
defer sc.mux.Unlock()
if depth <= 0 {
return
}
body, urls, err := fetcher.Fetch(url)
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("found: %s %q\n", url, body)
for _, u := range urls {
if sc.mp[u] == false{
sc.wg.Add(1)
go sc.Crawl(u, depth-1, fetcher)
}
}
return
}
func main() {
c := SafeCounter{mp: make(map[string]bool)}
c.wg.Add(1)
c.Crawl( "https://golang.org/", 4, fetcher)
c.wg.Wait()
}
all code:
package main
import (
"fmt"
"sync"
)
type Fetcher interface {
// Fetch 返回 URL 的 body 内容,并且将在这个页面上找到的 URL 放到一个 slice 中。
Fetch(url string) (body string, urls []string, err error)
}
type SafeCounter struct {
mp map[string]bool
mux sync.Mutex
wg sync.WaitGroup
}
// Crawl 使用 fetcher 从某个 URL 开始递归的爬取页面,直到达到最大深度。
func (sc *SafeCounter)Crawl(url string, depth int, fetcher Fetcher) {
defer sc.wg.Done()
sc.mux.Lock()
sc.mp[url] = true
defer sc.mux.Unlock()
if depth <= 0 {
return
}
body, urls, err := fetcher.Fetch(url)
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("found: %s %q\n", url, body)
for _, u := range urls {
if sc.mp[u] == false{
sc.wg.Add(1)
go sc.Crawl(u, depth-1, fetcher)
}
}
return
}
func main() {
c := SafeCounter{mp: make(map[string]bool)}
c.wg.Add(1)
c.Crawl( "https://golang.org/", 4, fetcher)
c.wg.Wait()
}
// fakeFetcher 是返回若干结果的 Fetcher。
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)
}
// fetcher 是填充后的 fakeFetcher。
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/",
},
},
}