Go: fatal error: all goroutines are asleep - deadlock

Go: fatal error: all goroutines are asleep - deadlock

我有一个文本文件,里面只有一行字。我想将所有这些单词单独存储在一个频道中,然后将它们从频道中提取出来并一个一个地打印出来。我有以下代码:

func main() {
    f, _ := os.Open("D:\input1.txt")
    scanner := bufio.NewScanner(f)
    file1chan := make(chan string)   
    for scanner.Scan() {
        line := scanner.Text()

        // Split the line on a space
        parts := strings.Fields(line)

        for i := range parts {   
            file1chan <- parts[i]
        }    
    }
    print(file1chan)
}

func print(in <-chan string) {
    for str := range in {
        fmt.Printf("%s\n", str)
    }
}

但是当我 运行 它时,我得到以下错误:

fatal error: all goroutines are asleep - deadlock!

goroutine 1 [chan send]: main.main()

我尝试在网上查找它,但我仍然无法修复它。谁能告诉我为什么会这样,我该如何解决?

谢谢!

您的 file1chan 是无缓冲的,因此当您尝试通过该通道发送一个值时,它会永远阻塞,等待某人获取一个值。

您需要启动一个新的goroutine,或者使通道缓冲并将其用作数组。这是带有另一个 goroutine 的版本:

func main() {
    f, _ := os.Open("D:\input1.txt")
    scanner := bufio.NewScanner(f)
    file1chan := make(chan string)
    go func() { // start a new goroutine that sends strings down file1chan 
        for scanner.Scan() {
            line := scanner.Text()

            // Split the line on a space
            parts := strings.Fields(line)

            for i := range parts {
                file1chan <- parts[i]
            }
        }
        close(file1chan)
    }()
    print(file1chan) // read strings from file1chan
}

func print(in <-chan string) {
    for str := range in {
        fmt.Printf("%s\n", str)
    }
}

这里是缓冲版本,只处理一个字符串:

func main() {
    f, _ := os.Open("D:\input1.txt")
    scanner := bufio.NewScanner(f)
    file1chan := make(chan string, 1) // buffer size of one
    for scanner.Scan() {
        line := scanner.Text()

        // Split the line on a space
        parts := strings.Fields(line)

        for i := range parts {
            file1chan <- parts[i]
        }
    }
    close(file1chan) // we're done sending to this channel now, so we close it.
    print(file1chan)
}

func print(in <-chan string) {
    for str := range in { // read all values until channel gets closed
        fmt.Printf("%s\n", str)
    }
}