登录
首页 >  Golang >  Go问答

爬虫多线程的运行原理是什么?

来源:stackoverflow

时间:2024-02-28 17:18:26 457浏览 收藏

偷偷努力,悄无声息地变强,然后惊艳所有人!哈哈,小伙伴们又来学习啦~今天我将给大家介绍《爬虫多线程的运行原理是什么?》,这篇文章主要会讲到等等知识点,不知道大家对其都有多少了解,下面我们就一起来看一吧!当然,非常希望大家能多多评论,给出合理的建议,我们一起学习,一起进步!

问题内容

我正在尝试解决有关使用缓存并行获取 url 以避免重复的任务。 我找到了正确的解决方案并且可以理解它。我看到正确的答案包含通道,并且 gorutine 通过 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/",
        },
    },
}

更新: 执行结果:

found: http://golang.org/ "the go programming language"

process finished with exit code 0

当我启动 goroutine 时,我感觉没有递归。但是如果在检查 url 是否在 cahce 中的线上设置断点,我得到这个:

found: http://golang.org/ "the go programming language"
found: http://golang.org/pkg/ "packages"

debugger finished with exit code 0

所以这意味着递归有效,但是出了问题,我猜是某种竞赛? 当在 runes 例程的行上添加第二个断点时,会发生更有趣的事情:

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

解决方案


在所有 go crawl() 调用完成之前,您的 main() 不会阻塞,因此退出。您可以使用 sync.waitgroup 或通道来同步程序,以完成所有 goroutine。

我还发现 goroutine 中使用的变量 u 存在问题;当执行 goroutine 时,范围循环可能会或可能不会更改 u 的值。

crawl 的结尾可能看起来像这样解决这两个问题;

wg := sync.WaitGroup{}

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()
        wg.Add(1)
        go func(url string) {
            Crawl(url, depth-1, fetcher)
            wg.Done()
        }(u)
    } else {
        cache.mux.Unlock()
    }
}

// Block until all goroutines are done
wg.Wait()

return

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>