jjzjj

去旅行练习 : Web Crawler - all goroutines are asleep - deadlock

coder 2024-07-06 原文

练习来自:https://tour.golang.org/concurrency/10

描述:

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.

Hint: you can keep a cache of the URLs that have been fetched on a map, but maps alone are not safe for concurrent use!

这是我的答案:

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 crawledURLs = make(map[string]bool)
var mux sync.Mutex

func CrawlURL(url string, depth int, fetcher Fetcher, quit chan bool) {
    defer func() { quit <- true }()
    if depth <= 0 {
        return
    }

    mux.Lock()
    _, isCrawled := crawledURLs[url]
    if isCrawled {
        return
    }
    crawledURLs[url] = true
    mux.Unlock()

    body, urls, err := fetcher.Fetch(url)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Printf("found: %s %q\n", url, body)
    quitThis := make(chan bool)
    for _, u := range urls {
        go CrawlURL(u, depth-1, fetcher, quitThis)
    }
    for range urls {
        <-quitThis
    }
    return
}

// Crawl uses fetcher to recursively crawl
// pages starting with url, to a maximum of depth.
func Crawl(url string, depth int, fetcher Fetcher) {
    CrawlURL(url, depth, fetcher, make(chan bool))
    return
}

func main() {
    Crawl("https://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{
    "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/",
        },
    },
}

输出:

found: https://golang.org/ "The Go Programming Language"
not found: https://golang.org/cmd/
found: https://golang.org/pkg/ "Packages"
found: https://golang.org/pkg/os/ "Package os"
fatal error: all goroutines are asleep - deadlock!

我想知道为什么会发生死锁?是不是我用错了 channel ?


注意到我忘记释放 if isCrawled {} 分支中的互斥量, 所以我像这样编辑了我的代码:

...
    if isCrawled {
        mux.Unlock() // added this line
        return
    }
...

但是死锁依然存在,输出结果不同:

found: https://golang.org/ "The Go Programming Language"
not found: https://golang.org/cmd/
found: https://golang.org/pkg/ "Packages"
found: https://golang.org/pkg/os/ "Package os"
found: https://golang.org/pkg/fmt/ "Package fmt"
fatal error: all goroutines are asleep - deadlock!

最佳答案

主要问题是您在 if isCrawled {} 中返回之前忘记释放互斥体。分支。

此外,如果您确实需要同步 goroutine,我建议使用同步 API。 channel 更适合用于通信和共享数据。

这是 sync.WaitGroup 的解决方案: https://play.golang.org/p/slrnmr3sPrs

这里是只有 channel 的解决方案:https://play.golang.org/p/FbPXxPSXvFL

问题是你第一次调用 CrawlURL()你不是从你作为论点传递的 channel 阅读。因此,一旦该函数尝试通过 defer func() { quit <- true }() 向其中发送内容。 ,它永远阻塞并且永远不会返回。

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 crawledURLs = make(map[string]bool)
var mux sync.Mutex

func CrawlURL(url string, depth int, fetcher Fetcher, quit chan bool) {
    //For very first function instance, this would block forever if 
    //nobody is receiving from the other end of this channel
    defer func() { quit <- true }()

    if depth <= 0 {
        return
    }

    mux.Lock()
    _, isCrawled := crawledURLs[url]
    if isCrawled {
        mux.Unlock()
        return
    }
    crawledURLs[url] = true
    mux.Unlock()

    body, urls, err := fetcher.Fetch(url)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Printf("found: %s %q\n", url, body)
    quitThis := make(chan bool)
    for _, u := range urls {
        go CrawlURL(u, depth-1, fetcher, quitThis)
    }
    for range urls {
        <-quitThis
    }
    return
}

// Crawl uses fetcher to recursively crawl
// pages starting with url, to a maximum of depth.
func Crawl(url string, depth int, fetcher Fetcher) {
    lastQuit := make(chan bool)
    go CrawlURL(url, depth, fetcher, lastQuit)
    //You need to receive from this channel in order to
    //unblock the called function
    <-lastQuit
    return
}

func main() {
    Crawl("https://golang.org/", 10, 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{
    "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/",
        },
    },
}

关于去旅行练习 : Web Crawler - all goroutines are asleep - deadlock,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56882761/

有关去旅行练习 : Web Crawler - all goroutines are asleep - deadlock的更多相关文章

  1. 牛客网专项练习30天Pytnon篇第02天 - 2

    1.在Python3中,下列关于数学运算结果正确的是:(B)a=10b=3print(a//b)print(a%b)print(a/b)A.3,3,3.3333...B.3,1,3.3333...C.3.3333...,3.3333...,3D.3.3333...,1,3.3333...解析:    在Python中,//表示地板除(向下取整),%表示取余,/表示除(Python2向下取整返回3)2.如下程序Python2会打印多少个数:(D)k=1000whilek>1:    print(k)k=k/2A.1000 B.10C.11D.9解析:    按照题意每次循环K/2,直到K值小于等

  2. ruby-on-rails - 解决 ruby​​ 中的旅行商问题(50 多个位置) - 2

    我在一家express公司工作。我们目前通过“手动”解决了50多个位置路线。我一直在考虑使用GoogleMapsAPI来解决这个问题,但我读到有24分的限制。目前我们在服务器中使用Rails,所以我正在考虑使用ruby​​脚本来获取50多个位置的坐标并输出合理的解决方案。您会使用什么算法来解决这个问题?Ruby是解决这类问题的好编程语言吗?你知道任何现有的ruby​​脚本吗? 最佳答案 这可能是您正在寻找的:警告:此站点被firefox标记为攻击站点-但我似乎没有。其实我之前用过没问题[检查URL的修订历史]rubyquiz似乎已关

  3. ruby-on-rails - Rails for Zombies Lab 4 > 练习 3 - 2

    我在第三个练习中停留在第四个RailsforZombies实验室。这是我的任务:创建将创建新僵尸的操作,然后重定向到创建的僵尸的显示页面。我有以下参数数组:params={:zombie=>{:name=>"Greg",:graveyard=>"TBA"}}我写了下面的代码作为解决方案:defcreate@zombie=Zombie.create@zombie.name=params[:zombie[:name]]@zombie.graveyard=params[:zombie[:graveyard]]@zombie.saveredirect_to(create_zombie_path

  4. javascript - Eloquent JavaScript 2nd Edition 递归练习解答 - 2

    我试图解决在线书籍eloquentjavascript2ndedition的递归练习:问题是这样的:We’veseenthat%(theremainderoperator)canbeusedtotestwhetheranumberisevenoroddbyusing%2tocheckifit’sdivisiblebytwo.Here’sanotherwaytodefinewhethera(positive,whole)numberisevenorodd:Zeroiseven.Oneisodd.ForanyothernumberN,itsevennessisthesameasN-2.De

  5. javascript - 对javascript练习的困惑 - 2

    我刚拿到DouglasCrockford的Javascript:TheGoodParts,我在理解他关于原型(prototype)的示例之一时遇到了一些困难。书中代码如下:if(typeofObject.create!=="function"){Object.create=function(o){varF=function(){}F.prototype=o;returnnewF;};}我假设此代码用于定位函数的原型(prototype)。但为什么要使用如此复杂的方法呢?为什么不直接使用variable.prototype?Crockford是Javascript方面的领先专家,因此我确

  6. javascript - 练习 Javascript 的最佳环境 - 2

    按照目前的情况,这个问题不适合我们的问答形式。我们希望答案得到事实、引用或专业知识的支持,但这个问题可能会引发辩论、争论、投票或扩展讨论。如果您觉得这个问题可以改进并可能重新打开,visitthehelpcenter指导。关闭11年前。我目前有Notepad++和AptanaStudio。是否有任何其他开发环境可以简化javascript代码的编写?谢谢。

  7. Javascript 练习 - 反转二维数组 - 2

    反转二维数组的值,可以扩展n次。[1,[2,[3,...[n,null]]]]给定:所有数组的长度始终为2列表中的最后一个数组将包含一个null索引1示例:[1,[2,[3,null]]]将输出[3,[2,[1,null]]][1,[2,[3,[4,null]]]]会输出[4,[3,[2,[1,null]]]]我不确定我描述的是否正确,但我今天遇到了这个练习并想出了一个相当明显的解决方案。varars=[1,[2,[3,null]]],rev=null;functionr(x){rev=(rev==null)?[x[0]]:[x[0],rev];if(x[1]!==null)r(x[1

  8. 华为eNSP网络配置综合练习一(vlan +MSTP+VLANif+VRRP+ 静态路由+单臂路由+STP+BFD) - 2

    综合练习一题目要求:实验范图实现PC机之间互通配置思路:配置过程:配置终端设备及3700交换机实现此案例需要按照如下步骤进行。1)配置PC的IP地址和网关2)配置SW1/5/6的vlan为10/20/30,交换机之间的链路为Trunk,与PC间为Access3)配置SW2/3/7的vlan为40/50,交换机之间的链路为Trunk,与PC间为Access4)配置SW4/8/9的vlan为60/70/80,交换机之间的链路为Trunk,与PC间为Access5)配置R1/R2/R3的接口IP地址6)配置每个VLAN的网关接口IP地址SW1为vlan10/20/30的网关设备:interfacev

  9. 智能合约学习笔记一 、——{Solidity语言详解——(1—2)小练习} - 2

    1.要求:1.根据提示,在指定位置写出编译版本,要求使用^符号,版本要求在0.6.0及以上。2.根据提示,在指定位置写出所定义的合约名称。3.为了查看程序的效果,我们使用在线Solidity开发工具RemixIDE编译和运行Solidity程序。中文在线版:在浏览器打开下方链接: Remix-中文版-智谷星图。第1步–在文件浏览器选项卡下,新建一个Firstapp.sol文件,把我们补充完整的代码直接复制过来。第2步–在SOLIDITY编译器选项卡下,选择0.6.5的那个编译器版本并单击 编译Firstapp.sol 按钮,开始编译。编译成功后会根据本地客户端和版本内容弹出提示,可以不用处理。

  10. javascript - 我需要一些初级程序员的简单逻辑/编程练习 - 2

    关闭。这个问题不符合StackOverflowguidelines.它目前不接受答案。要求我们推荐或查找工具、库或最喜欢的场外资源的问题对于StackOverflow来说是偏离主题的,因为它们往往会吸引自以为是的答案和垃圾邮件。相反,describetheproblem以及迄今为止为解决该问题所做的工作。关闭9年前。Improvethisquestion我目前正在教员工ECMA脚本,因为维护我们使用的工作流系统需要它,我需要一些挑战作为练习。我们已经涵盖了大部分语言,他现在非常熟悉语法,所以我只需要他开始使用它。我需要给他提供练习,让他进行逻辑思考。例如,他了解什么是if和switch

随机推荐