Go:致命错误:所有 goroutine 都处于睡眠状态 - 死锁

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


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)

    }

}

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


致命错误:所有 goroutine 都处于睡眠状态 - 死锁!


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


我尝试在网上查找它,但我仍然无法修复它。谁能告诉我为什么会发生这种情况以及我如何解决它?


莫回无
浏览 169回答 1
1回答

凤凰求蛊

您file1chan是无缓冲的,因此当您尝试通过该通道发送值时,它会永远阻塞,等待某人获取值。您需要启动一个新的 goroutine,或者使通道缓冲并将其用作数组。这是带有另一个 goroutine 的版本:func main() {&nbsp; &nbsp; f, _ := os.Open("D:\\input1.txt")&nbsp; &nbsp; scanner := bufio.NewScanner(f)&nbsp; &nbsp; file1chan := make(chan string)&nbsp; &nbsp; go func() { // start a new goroutine that sends strings down file1chan&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; for scanner.Scan() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; line := scanner.Text()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Split the line on a space&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; parts := strings.Fields(line)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for i := range parts {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; file1chan <- parts[i]&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; close(file1chan)&nbsp; &nbsp; }()&nbsp; &nbsp; print(file1chan) // read strings from file1chan}func print(in <-chan string) {&nbsp; &nbsp; for str := range in {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("%s\n", str)&nbsp; &nbsp; }}这是缓冲版本,仅用于处理单个字符串:func main() {&nbsp; &nbsp; f, _ := os.Open("D:\\input1.txt")&nbsp; &nbsp; scanner := bufio.NewScanner(f)&nbsp; &nbsp; file1chan := make(chan string, 1) // buffer size of one&nbsp; &nbsp; for scanner.Scan() {&nbsp; &nbsp; &nbsp; &nbsp; line := scanner.Text()&nbsp; &nbsp; &nbsp; &nbsp; // Split the line on a space&nbsp; &nbsp; &nbsp; &nbsp; parts := strings.Fields(line)&nbsp; &nbsp; &nbsp; &nbsp; for i := range parts {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; file1chan <- parts[i]&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; close(file1chan) // we're done sending to this channel now, so we close it.&nbsp; &nbsp; print(file1chan)}func print(in <-chan string) {&nbsp; &nbsp; for str := range in { // read all values until channel gets closed&nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("%s\n", str)&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go