首页 > 解决方案 > 为什么我的代码在没有关闭通道的情况下陷入僵局?

问题描述

我正在尝试编写一个程序:

package main

import (
    "fmt"
    "sync"
)

func main() {
    n := 4
    resChan := make(chan []int, n)
    res := []int{}
    var wg sync.WaitGroup
    for i := 0; i < n; i++ {
        wg.Add(1)
        go func(i int) {
            defer wg.Done()
            resChan <- append(res, i)
        }(i)
    }
    wg.Wait()

    close(resChan) // code will deadlock without this
    for subRes := range resChan {
        res = append(res, subRes...)
    }
    fmt.Printf("%v", res)
}

我认为我有一个缓冲通道,因此对通道的写入不会阻塞。但是,我得到了:

fatal error: all goroutines are asleep - deadlock!

goroutine 1 [chan receive]:
main.main()
    /tmp/sandbox562058728/prog.go:23 +0x14c

有人可以解释为什么代码会这样吗?

标签: go

解决方案


在通道关闭之前,测距通道不会退出 for 循环。


推荐阅读