美文网首页
channel之阻塞四

channel之阻塞四

作者: anthonydan | 来源:发表于2020-03-17 00:35 被阅读0次

    搞不懂这个为什么会panic

    package main
    
    import (
        "fmt"
        "sync"
        "time"
    )
    
    func main() {
        var wg sync.WaitGroup
        var ch chan int // 未初始化,值为 nil
        end := make(chan struct{})
        ch = make(chan int)
        for i := 0; i < 3; i++ {
            wg.Add(1)
            go func(i int, group *sync.WaitGroup) {
                defer group.Done()
                ch <- i
            }(i, &wg)
        }
    
        go func() {
            fmt.Println("start range")
            for v := range ch {
                fmt.Println("range ing")
                fmt.Println(v)
            }
    
            end <- struct{}{}
        }()
    
        time.Sleep(3*time.Second)
        ch <- 4
    
        wg.Wait()
        time.Sleep(3*time.Second)
        //close(ch)
        <-end
    
        //var ch chan int // 未初始化,值为 nil
        //ch = make(chan int)
        //for i := 0; i < 3; i++ {
        //  go func(i int) {
        //      ch <- i
        //  }(i)
        //}
        //for v := range ch {
        //  fmt.Println(v)
        //}
        //close(ch)
        //time.Sleep(2 * time.Second)
    }
    

    相关文章

      网友评论

          本文标题:channel之阻塞四

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