美文网首页
【Go】随笔1

【Go】随笔1

作者: 如雨随行2020 | 来源:发表于2022-11-19 16:46 被阅读0次

channel死锁

首先,如果一个channel还没有被初始化,从里面读数据是会阻塞的,那么有没有方式恢复呢,看下面例子

func main() {
    var ch chan int
    go func() {
        for {
            select {
            case <-ch:
                fmt.Println("ok")
            default:
                time.Sleep(time.Second)
                fmt.Println("default")
            }
        }
    }()
    time.Sleep(time.Second)
    ch = make(chan int, 100)
    fmt.Println("send 1")
    ch <- 1
    time.Sleep(5 * time.Second)
    fmt.Println("over")
}

输出

image-20221120155601032

但是如果将default注释,那么后续无法恢复

image-20221120155715121

所以:不能channel必须先初始化,才能去receive,除非使用default的场景

相关文章

网友评论

      本文标题:【Go】随笔1

      本文链接:https://www.haomeiwen.com/subject/ztwbxdtx.html