golang tour webcrawler练习的简单解决方案

Simple solution for golang tour webcrawler exercise

我是 Go 的新手,我看到了这个练习的一些解决方案,但我认为它们很复杂...

在我的解决方案中,一切看起来都很简单,但我遇到了死锁错误。我不知道如何正确关闭通道并停止主块内的循环。有没有简单的方法可以做到这一点?

Solution on Golang playground

感谢 any/all 可能提供的帮助!

package main

import (
    "fmt"
    "sync"
)

type Fetcher interface {
    // Fetch returns the body of URL and
    // a slice of URLs found on that page.
    Fetch(url string) (body string, urls []string, err error)
}

type SafeCache struct {
    cache map[string]bool
    mux   sync.Mutex
}

func (c *SafeCache) Set(s string) {
    c.mux.Lock()
    c.cache[s] = true
    c.mux.Unlock()
}

func (c *SafeCache) Get(s string) bool {
    c.mux.Lock()
    defer c.mux.Unlock()
    return c.cache[s]
}

var (
    sc = SafeCache{cache: make(map[string]bool)}
    errs, ress = make(chan error), make(chan string)
)

// Crawl uses fetcher to recursively crawl
// pages starting with url, to a maximum of depth.
func Crawl(url string, depth int, fetcher Fetcher) {
    if depth <= 0 {
        return
    }

    var (
        body string
        err error
        urls []string
    )

    if ok := sc.Get(url); !ok {
        sc.Set(url)
        body, urls, err = fetcher.Fetch(url)
    } else {
        err = fmt.Errorf("Already fetched: %s", url)
    }

    if err != nil {
        errs <- err
        return
    }

    ress <- fmt.Sprintf("found: %s %q\n", url, body)
    for _, u := range urls {
        go Crawl(u, depth-1, fetcher)
    }
    return
}

func main() {
    go Crawl("http://golang.org/", 4, fetcher)
    for {
        select {
        case res, ok := <-ress:
            fmt.Println(res)
            if !ok {
                break
            }
        case err, ok := <-errs:
            fmt.Println(err)
            if !ok {
                break
            }
        }
    }
}

// fakeFetcher is Fetcher that returns canned results.
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 is a populated fakeFetcher.
var fetcher = fakeFetcher{
    "http://golang.org/": &fakeResult{
        "The Go Programming Language",
        []string{
            "http://golang.org/pkg/",
            "http://golang.org/cmd/",
        },
    },
    "http://golang.org/pkg/": &fakeResult{
        "Packages",
        []string{
            "http://golang.org/",
            "http://golang.org/cmd/",
            "http://golang.org/pkg/fmt/",
            "http://golang.org/pkg/os/",
        },
    },
    "http://golang.org/pkg/fmt/": &fakeResult{
        "Package fmt",
        []string{
            "http://golang.org/",
            "http://golang.org/pkg/",
        },
    },
    "http://golang.org/pkg/os/": &fakeResult{
        "Package os",
        []string{
            "http://golang.org/",
            "http://golang.org/pkg/",
        },
    },
}

你可以用 sync.WaitGroup

解决这个问题
  1. 您可以开始在单独的 goroutine 中收听您的频道。
  2. WaitGroup 将协调你有多少个 goroutines。

wg.Add(1) 说我们要启动新的 goroutine。

wg.Done() 表示 goroutine 完成了。

wg.Wait() 阻塞 goroutine,直到所有启动的 goroutine 都没有完成。

这 3 个方法可以让你协调 goroutines。

Go playground link

PS。您可能对 sync.RWMutex 感兴趣,因为您的 SafeCache