加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

golang:goroute with select不会停止,除非我添加了fmt.Print()

发布时间:2020-12-16 19:21:04 所属栏目:大数据 来源:网络整理
导读:我试过Go Tour exercise #71 如果它运行像go run 71_hang.go ok,它运行正常. 但是,如果你使用go run 71_hang.go nogood,它将永远运行. 唯一的区别是select语句中默认的额外fmt.Print(“”). 我不确定,但我怀疑某种无限循环和竞争条件?这是我的解决方案. 注
我试过Go Tour exercise #71

如果它运行像go run 71_hang.go ok,它运行正常.

但是,如果你使用go run 71_hang.go nogood,它将永远运行.

唯一的区别是select语句中默认的额外fmt.Print(“”).

我不确定,但我怀疑某种无限循环和竞争条件?这是我的解决方案.

注意:Go没有抛出并不是死锁:所有的goroutines都睡着了 – 僵局!

package main

import (
    "fmt"
    "os"
)

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

func crawl(todo Todo,fetcher Fetcher,todoList chan Todo,done chan bool) {
    body,urls,err := fetcher.Fetch(todo.url)
    if err != nil {
        fmt.Println(err)
    } else {
        fmt.Printf("found: %s %qn",todo.url,body)
        for _,u := range urls {
            todoList <- Todo{u,todo.depth - 1}
        }
    }
    done <- true
    return
}

type Todo struct {
    url   string
    depth int
}

// Crawl uses fetcher to recursively crawl
// pages starting with url,to a maximum of depth.
func Crawl(url string,depth int,fetcher Fetcher) {
    visited := make(map[string]bool)
    doneCrawling := make(chan bool,100)
    toDoList := make(chan Todo,100)
    toDoList <- Todo{url,depth}

    crawling := 0
    for {
        select {
        case todo := <-toDoList:
            if todo.depth > 0 && !visited[todo.url] {
                crawling++
                visited[todo.url] = true
                go crawl(todo,fetcher,toDoList,doneCrawling)
            }
        case <-doneCrawling:
            crawling--
        default:
            if os.Args[1]=="ok" {   // *
                fmt.Print("")
            }
            if crawling == 0 {
                goto END
            }
        }
    }
END:
    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/pkg/fmt/","http://golang.org/pkg/os/","http://golang.org/pkg/fmt/": &fakeResult{
        "Package fmt","http://golang.org/pkg/","http://golang.org/pkg/os/": &fakeResult{
        "Package os",}
在select中添加默认语句会改变select的工作方式.如果没有默认语句,select将阻止等待通道上的任何消息.使用默认语句select会在每次从通道中读取任何内容时运行默认语句.在你的代码中,我认为这是一个无限循环.将fmt.Print语句放入允许调度程序安排其他goroutine.

如果您更改这样的代码,那么它可以正常工作,使用非阻塞方式选择,允许其他goroutine正常运行.

for {
        select {
        case todo := <-toDoList:
            if todo.depth > 0 && !visited[todo.url] {
                crawling++
                visited[todo.url] = true
                go crawl(todo,doneCrawling)
            }
        case <-doneCrawling:
            crawling--
        }
        if crawling == 0 {
            break
        }
    }

如果使用GOMAXPROCS = 2,则可以使原始代码生效,这是调度程序在无限循环中忙碌的另一个提示.

请注意,goroutines是合作安排的.我不完全了解你的问题是选择是goroutine应该产生的一个点 – 我希望其他人可以解释为什么它不在你的例子中.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读