go - 为什么我的代码在不关闭 channel 的情况下处于死锁状态?

标签 go

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

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)
}
我以为我有一个缓冲的 channel ,因此不会阻塞对该 channel 的写入。但是,我得到了:
fatal error: all goroutines are asleep - deadlock!

goroutine 1 [chan receive]:
main.main()
    /tmp/sandbox562058728/prog.go:23 +0x14c
有人可以解释为什么代码会这样吗?

最佳答案

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

关于go - 为什么我的代码在不关闭 channel 的情况下处于死锁状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63643641/

相关文章:

http - http请求是否自动重试?

data-structures - Golang 中的 map 访问瓶颈

go - 当我添加表达式 "fmt.Println()"时发生了什么

go - 下一个goroutine什么时候执行?

firebase - 连接到 Firebase 存储桶

go - 在 go 应用程序中传递要评估的表达式?

go - 在 golang 中发送带附件的电子邮件

windows - 在 Go 中请求 UAC 提升

go - _mm_add_epi32的Golang汇编工具

go - 在Go中附加为指针的局部变量的生命周期