猿问

致命错误所有 goroutine 都处于休眠状态,死锁

你能解释一下下面的错误吗:fatal error:

true

true

all goroutines are sleep - deadlock!


package main


import (

    "fmt"

)


func printer(ch chan bool) {

    ch <- true

}


func main() {

    var c chan bool = make(chan bool, 2)


    for i := 0; i < 5; i++ {

        go printer(c)

    }


    for i := range c {

        fmt.Println(i)

    }

}


慕虎7371278
浏览 140回答 1
1回答

jeck猫

因为通道c没有关闭,所以范围循环不会退出。此代码不会阻塞:func main() {&nbsp; var c chan bool = make(chan bool, 2)&nbsp; for i := 0; i < 5; i++ {&nbsp; &nbsp; go printer(c)&nbsp; }&nbsp; for i := 0; i < 5; i++ {&nbsp; &nbsp; fmt.Println(<-c)&nbsp; }}playground example
随时随地看视频慕课网APP

相关分类

Go
我要回答