go - 何时何地检查 channel 是否不会获得更多数据?

标签 go

我正在尝试解决 Exercise: Web Crawler

In this exercise you'll use Go's concurrency features to parallelize a web crawler.

Modify the Crawl function to fetch URLs in parallel without fetching the same URL twice.

我什么时候应该检查所有的 url 是否已经被抓取? (或者我怎么知道是否不会有更多的数据排队?)

package main

import (
    "fmt"
)

type Result struct {
    Url string
    Depth int
}

type Stor struct {
    Queue  chan Result
    Visited map[string]int
}    

func NewStor() *Stor {
    return &Stor{
        Queue:  make(chan Result,1000),
        Visited: map[string]int{},
    }
}

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)
}

// Crawl uses fetcher to recursively crawl
// pages starting with url, to a maximum of depth.
func Crawl(res Result, fetcher Fetcher, stor *Stor) {
    defer func() {          
        /*
        if len(stor.Queue) == 0 {
            close(stor.Queue)
        }   
        */  // this is wrong, it makes the channel closes too early
    }()
    if res.Depth <= 0 {
        return
    }
    // TODO: Don't fetch the same URL twice.
    url := res.Url
    stor.Visited[url]++
    if stor.Visited[url] > 1 {
        fmt.Println("skip:",stor.Visited[url],url)
        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 {
        stor.Queue <- Result{u,res.Depth-1}
    }
    return
}

func main() {
    stor := NewStor()   
    Crawl(Result{"http://golang.org/", 4}, fetcher, stor)
    for res := range stor.Queue {
        // TODO: Fetch URLs in parallel.
        go Crawl(res,fetcher,stor)
    }
}

// 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/",
        },
    },
}

输出是死锁,因为 stor.Queue channel 从未关闭。

最佳答案

等待所有 goroutings 完成的最简单方法是同步包中的 sync.WaitGroup

package main
import "sync"
var wg sync.WaitGroup
//then you do
func Crawl(res Result, fetcher Fetcher) { //what for you pass stor *Stor as arg? It just visible for all goroutings
    defer wg.Done()
...
//why not to spawn new routing just inside Crowl?
    for res := range urls {
        wg.Add(1)
        go Crawl(res,fetcher)
    }
...
}
...
//And in main.main()
func main() {
    wg.Add(1) 
    Crawl(Result{"http://golang.org/", 4}, fetcher)
    ...
    wg.Wait() //Will block until all routings Done
}

完整的解决方案将是:

package main

import (
    "fmt"
    "sync"
)
var wg sync.WaitGroup
var visited map[string]int = map[string]int{}

type Result struct {
    Url string
    Depth int
}

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)
}

// Crawl uses fetcher to recursively crawl
// pages starting with url, to a maximum of depth.
func Crawl(res Result, fetcher Fetcher) {
    defer wg.Done()
    if res.Depth <= 0 {
        return
    }
    // TODO: Don't fetch the same URL twice.
    url := res.Url
    visited[url]++
    if visited[url] > 1 {
        fmt.Println("skip:",visited[url],url)
        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 {
        wg.Add(1)
        go Crawl( Result{u,res.Depth-1},fetcher)
        //stor.Queue <- Result{u,res.Depth-1}
    }
    return
}

func main() {
    wg.Add(1) 
    Crawl(Result{"http://golang.org/", 4}, fetcher)
    wg.Wait()
}

// 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/",
        },
    },
}

关于go - 何时何地检查 channel 是否不会获得更多数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27841092/

相关文章:

go - 在go ent框架中创建基础实体

windows - 如何在golang中获取英文错误信息?

go - 如何部署带有自定义go构建约束/标签的golang谷歌云功能?

git - 当 $PATH 中有多个 git 可用时, 'go get' 使用哪个 git 版本?

go - 如何获取 golang proto 生成的复杂结构中的所有字段名称

python - Go语言中runtime-gdb.py的作用是什么?

go - 分布式 Go 的框架(如 Erlang OTP)?

intellij-idea - (Go) 如何在 IntelliJ IDEA 上使用 GDB 调试?

algorithm - slice 神奇地更新

go - 如何获取可用 TCP 数据的大小?