登录
首页 >  Golang >  Go问答

致命错误:所有 goroutine 堵塞 - 死锁风险! Go 之旅 - Webcrawler

来源:stackoverflow

时间:2024-02-28 14:27:26 128浏览 收藏

在Golang实战开发的过程中,我们经常会遇到一些这样那样的问题,然后要卡好半天,等问题解决了才发现原来一些细节知识点还是没有掌握好。今天golang学习网就整理分享《致命错误:所有 goroutine 堵塞 - 死锁风险! Go 之旅 - Webcrawler》,聊聊,希望可以帮助到正在努力赚钱的你。

问题内容

我正在尝试通过 go 之旅进行此练习。下面提供了我的解决方案,但我遇到了死锁错误。知道是什么原因造成的吗?

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 (
    mutex sync.mutex
    waitg sync.waitgroup
    cache = make(map[string]bool)
)

// 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 cache[url]{
        mutex.lock()
        fmt.println("duplicate: ", url)
        mutex.unlock()
        return
    }
        mutex.lock()
        fmt.println("none-duplicate: ", url)
        cache[url] = true
        mutex.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 {
        waitg.add(1)
        go crawl(u, depth-1, fetcher)
    }
    return

    waitg.done()
}

func main() {
    waitg.add(1)
    crawl("https://golang.org/", 4, fetcher)
    waitg.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{
    "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/",
        },
    },
}

我感到恐慌:

Duplicate:  https://golang.org/
fatal error: all goroutines are asleep - deadlock!

goroutine 1 [semacquire]:
sync.runtime_Semacquire(0x0)
    /usr/local/go-faketime/src/runtime/sema.go:56 +0x25
sync.(*WaitGroup).Wait(0x49a702)
    /usr/local/go-faketime/src/sync/waitgroup.go:130 +0x71
main.main()
    /tmp/sandbox943974961/prog.go:58 +0x55

正确答案


您的 waitg.wait() 将永远等待,因为 waitgroup 永远不会收到完成通知(例如使用 waitg.done())。 go 运行时足够智能,可以检测到这种情况并发出恐慌。

代码中存在许多问题导致这种情况:

  1. 无法访问的代码:

    return          // *nothing* happens after a return!
         waitg.done()    // this line will never execute.

    (注意编译器警告 - 大多数编译器都会警告无法访问的代码)

  2. 错误路径中缺少对 waitg.done() 的调用:

    if cache[url]{
         mutex.lock()
         fmt.println("duplicate: ", url)
         mutex.unlock()
         return          // oops forgot to call waitg.done() !!!
     }

    (其他错误路径同理)

对此的最佳解决方案是 defer 在函数开头调用 waitg.done()

func Crawl(url string, depth int, fetcher Fetcher) {
    defer waitG.Done()   // look ma, no need to worry about this later !!!
    // ... rest of the code ...

现在是 it works

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《致命错误:所有 goroutine 堵塞 - 死锁风险! Go 之旅 - Webcrawler》文章吧,也可关注golang学习网公众号了解相关技术文章。

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