channel之阻塞四

2020-03-17  本文已影响0人  anthonydan

搞不懂这个为什么会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)
}
上一篇下一篇

猜你喜欢

热点阅读