select - golang : goroute with select doesn't stop unless I added a fmt. 打印()

标签 select go channel goroutine

我尝试了 Go Tour exercise #71

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

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

唯一的区别是 select 语句中的 default 中多了一个 fmt.Print("")

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

注意:这不是死锁,因为 Go 没有 throw: all goroutines are sleep - 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/",
        },
    },
}

最佳答案

select 中放置一个 default 语句会改变 select 的工作方式。如果没有默认语句,select 将阻止等待 channel 上的任何消息。使用默认语句 select 将在每次没有可从 channel 读取的内容时运行默认语句。在您的代码中,我认为这会造成无限循环。放入 fmt.Print 语句允许调度程序调度其他 goroutine。

如果您像这样更改您的代码,那么它可以正常工作,以非阻塞方式使用 select,从而允许其他 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
        }
    }

如果您使用 GOMAXPROCS=2,您可以使您的原始代码正常工作,这是调度程序忙于无限循环的另一个暗示。

请注意,goroutines 是合作调度的。关于您的问题,我不完全理解的是 select 是 goroutine 应该屈服的点 - 我希望其他人可以解释为什么它不在您的示例中。

关于select - golang : goroute with select doesn't stop unless I added a fmt. 打印(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12615955/

相关文章:

mysql - 计算两个日期之间的差异

http - 如何在 Go 中自定义 http.Client 或 http.Transport 以在超时后重试?

go - 停止阻塞的 goroutine

go - 使用 Go 检查 channel 是否具有准备读取的值

parsing - 具有动态模式的 Golang 和 yaml

caching - channel 并发保证

sql - 选择在 X 月和 Y 或 Z 月购买的客户

php - MySQL 使用不存在列中的数组

html - 想在选择框中显示有限的数字

go - 使用 goroutine 运行 cmd.Wait() 时的错误处理