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

Sun*_*gam 6 select channel go goroutine

我尝试了Go Tour 练习#71

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

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

唯一的区别是额外fmt.Print("")defaultselect语句.

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

注意:Go并没有死锁 throw: all goroutines are asleep - deadlock!

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 %q\n", 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/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/",
        },
    },
}
Run Code Online (Sandbox Code Playgroud)

Nic*_*ood 15

把一个default语句进行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, fetcher, toDoList, doneCrawling)
            }
        case <-doneCrawling:
            crawling--
        }
        if crawling == 0 {
            break
        }
    }
Run Code Online (Sandbox Code Playgroud)

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

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


Phi*_*lip 5

你有100%的CPU负载,因为几乎所有的时候都会执行默认情况,因此它会被无限循环,因为它一遍又一遍地执行.在这种情况下,Go调度程序不会通过设计将控制权交给另一个goroutine.所以任何其他goroutine永远都没有机会设置crawling != 0,你有无限循环.

在我看来,如果你想使用select语句,你应该删除默认情况,而是创建另一个频道.

否则,运行时包会帮助您以脏的方式:

  • runtime.GOMAXPROCS(2) 将工作(或导出GOMAXPROCS = 2),这样你将有多个OS执行线程
  • runtime.Gosched()不时在Crawl里面打电话.尽管CPU负载为100%,但这将明确地将控制权传递给另一个Goroutine.

编辑:是的,以及fmt.Printf产生影响的原因:因为它明确地将控制传递给某些系统调用... ...)