Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Go 在本例中,爬虫多线程是如何工作的?_Go - Fatal编程技术网

Go 在本例中,爬虫多线程是如何工作的?

Go 在本例中,爬虫多线程是如何工作的?,go,Go,我正在尝试解决有关使用缓存并行获取URL以避免重复的任务。 我找到了正确的解决方案,并且能够理解它。我看到正确的答案包含通道,并且gorutines通过chan在缓存中推送URL。但是为什么我的简单代码不能正常工作呢? 我不知道哪里出了错 package main import ( "fmt" "sync" ) type Fetcher interface { // Fetch returns the body of URL and // a slice of

我正在尝试解决有关使用缓存并行获取URL以避免重复的任务。 我找到了正确的解决方案,并且能够理解它。我看到正确的答案包含通道,并且gorutines通过chan在缓存中推送URL。但是为什么我的简单代码不能正常工作呢? 我不知道哪里出了错

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

var cache = struct {
    cache map[string]int
    mux sync.Mutex
}{cache: make(map[string]int)}

// Crawl uses fetcher to recursively crawl
// pages starting with url, to a maximum of depth.
func Crawl(url string, depth int, fetcher Fetcher) {
    // TODO: Fetch URLs in parallel.
    // TODO: Don't fetch the same URL twice.
    // This implementation doesn't do either:

    if depth <= 0 {
        return
    }
    cache.mux.Lock()
    cache.cache[url] = 1 //put url in cache
    cache.mux.Unlock()
    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 {
        cache.mux.Lock()
        if _, ok := cache.cache[u]; !ok { //check if url already in cache
            cache.mux.Unlock()
            go Crawl(u, depth-1, fetcher)
        } else {
            cache.mux.Unlock()
        }
    }
    return
}

func main() {
    Crawl("http://golang.org/", 4, fetcher)
}

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

当我启动goroutine时,我感觉没有递归。但如果在检查cahce中是否有URL的行上创建断点,我得到以下结果:

found: http://golang.org/ "The Go Programming Language"
found: http://golang.org/pkg/ "Packages"

Debugger finished with exit code 0
这意味着递归是可行的,但有些事情出了问题,我猜是种族? 在运行例程的第行添加第二个断点时,会发生更有趣的事情:

found: http://golang.org/ "The Go Programming Language"
found: http://golang.org/pkg/ "Packages"
fatal error: all goroutines are asleep - deadlock!

goroutine 1 [semacquire]:
sync.runtime_SemacquireMutex(0x58843c, 0x0, 0x1)
        /usr/local/go/src/runtime/sema.go:71 +0x47
sync.(*Mutex).lockSlow(0x588438)
        /usr/local/go/src/sync/mutex.go:138 +0x295
sync.(*Mutex).Lock(0x588438)
        /usr/local/go/src/sync/mutex.go:81 +0x58
main.Crawl(0x4e9cf9, 0x12, 0x4, 0x4f7700, 0xc00008c180)
        /root/go/src/crwaler/main.go:38 +0x46c
main.main()
        /root/go/src/crwaler/main.go:48 +0x57

goroutine 18 [semacquire]:
sync.runtime_SemacquireMutex(0x58843c, 0x0, 0x1)
        /usr/local/go/src/runtime/sema.go:71 +0x47
sync.(*Mutex).lockSlow(0x588438)
        /usr/local/go/src/sync/mutex.go:138 +0x295
sync.(*Mutex).Lock(0x588438)
        /usr/local/go/src/sync/mutex.go:81 +0x58
main.Crawl(0x4ea989, 0x16, 0x3, 0x4f7700, 0xc00008c180)
        /root/go/src/crwaler/main.go:38 +0x46c
created by main.Crawl
        /root/go/src/crwaler/main.go:41 +0x563

Debugger finished with exit code 0
您的
main()
不会阻塞,直到所有
go Crawl()
调用完成,然后退出。您可以使用
sync.WaitGroup
或通道来同步程序结束时所有goroutine的完成

我还发现goroutine中使用的变量
u
有问题;执行goroutine时,
u
的值可能已被范围循环更改,也可能未被更改

Crawl
的结尾可以像这样解决这两个问题


wg:=sync.WaitGroup{}
fmt.Printf(“找到:%s%q\n”,url,正文)
对于u,u:=范围URL{
cache.mux.Lock()
如果{,确定:=cache.cache[u];!确定{//检查url是否已在缓存中
cache.mux.Unlock()
工作组.添加(1)
go func(url字符串){
爬网(url、深度1、抓取器)
wg.Done()
}(u)
}否则{
cache.mux.Unlock()
}
}
//阻塞,直到完成所有goroutine
wg.Wait()
返回

我在你的代码中看到的一个问题是,当你使用cache.mux.Lock()时,你只在if中使用Unlock(),因此在缓存中找到url的一个goroutine将锁定其他所有人。另一个问题是,你应该在写入缓存时锁定它,现在你只在读取时锁定它。@MarioSantini你说得对!我添加了else条件来解锁互斥锁,结果不变。(当时也看到了关于写作和固定的内容)。但当我调试并在SPEP之间暂停时,它几乎可以正常工作,并找到了一个新的url。肯定还有另一个问题。。。我开始相信阻塞必须有点复杂,才能正常工作并避免死锁。所以,我应该使用通道来管理锁,还是有更简单的方法?要检查竞争条件,您应该使用go build上的-race选项。它应该突出显示一些问题。您也不会等待任何
go Crawl
调用返回,因此您可以获得任意数量的结果
found: http://golang.org/ "The Go Programming Language"
found: http://golang.org/pkg/ "Packages"
fatal error: all goroutines are asleep - deadlock!

goroutine 1 [semacquire]:
sync.runtime_SemacquireMutex(0x58843c, 0x0, 0x1)
        /usr/local/go/src/runtime/sema.go:71 +0x47
sync.(*Mutex).lockSlow(0x588438)
        /usr/local/go/src/sync/mutex.go:138 +0x295
sync.(*Mutex).Lock(0x588438)
        /usr/local/go/src/sync/mutex.go:81 +0x58
main.Crawl(0x4e9cf9, 0x12, 0x4, 0x4f7700, 0xc00008c180)
        /root/go/src/crwaler/main.go:38 +0x46c
main.main()
        /root/go/src/crwaler/main.go:48 +0x57

goroutine 18 [semacquire]:
sync.runtime_SemacquireMutex(0x58843c, 0x0, 0x1)
        /usr/local/go/src/runtime/sema.go:71 +0x47
sync.(*Mutex).lockSlow(0x588438)
        /usr/local/go/src/sync/mutex.go:138 +0x295
sync.(*Mutex).Lock(0x588438)
        /usr/local/go/src/sync/mutex.go:81 +0x58
main.Crawl(0x4ea989, 0x16, 0x3, 0x4f7700, 0xc00008c180)
        /root/go/src/crwaler/main.go:38 +0x46c
created by main.Crawl
        /root/go/src/crwaler/main.go:41 +0x563

Debugger finished with exit code 0