drrkgbm6851 2019-03-05 08:07
浏览 5

为什么所有goroutine都睡着了?

Following is the code;

package main

import "fmt"

func main() {
    func1(1)
}

func func1(n int) {
    ch := make(chan int)
    ch <- 1
        for i := range ch {
            fmt.Println(i)
            fmt.Println(<-ch)
        }   
}

When I try to execute this code, it throws the following error;

fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan send]:
main.func1(0x1, 0x432070)
    /tmp/sandbox451742015/main.go:11 +0x60
main.main()
    /tmp/sandbox451742015/main.go:6 +0x20
  • 写回答

1条回答 默认 最新

  • duanlushen8940 2019-03-05 08:20
    关注

    Your channel is unbuffered, so the first send on it will block until someone receives from it. But the code that would receive from it is after that, so this is an "immediate" deadlock.

    You could make it unbuffered like ch := make(chan int, 1), so the send would not block, but then you have a single goroutine that has a for range over a channel. This loop only exits if the channel gets closed, but you never close it. And you only send a single value on it, so the loop is blocked, waiting on values that it can receive or the channel to get closed.

    You need another goroutine that closes the channel sometime. And inside the loop, you do not need to receive again from the channel, the loop construct already does that. i will be a value received from the channel.

    Working example that makes any sense:

    func func1(n int) {
        ch := make(chan int)
        go func() {
            for i := 0; i < 5; i++ {
                ch <- i
            }
            close(ch)
        }()
        for i := range ch {
            fmt.Println(i)
        }
    }
    

    This outputs (try it on the Go Playground):

    0
    1
    2
    3
    4
    
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度