美文网首页
channel之阻塞六

channel之阻塞六

作者: anthonydan | 来源:发表于2020-03-17 00:45 被阅读0次
    //开启close(ch),看range end输出了。说明for range后面执行了
    
    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)
            }
            fmt.Println("range end")
            end <- struct{}{}
        }()
    
        time.Sleep(3*time.Second)
        ch <- 4
    
        wg.Wait()
        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)
    }
    

    //思考:假如wg.Wait已经执行,close(ch)还没执行,然而for range已经执行完,这时range end 不会输出?
    答案:会等待close(ch),然后输出range end。先知了后面还有close(ch)

    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)
            }
            fmt.Println("range end")
            end <- struct{}{}
        }()
    
        time.Sleep(1*time.Second)
        ch <- 4
    
        wg.Wait()
        time.Sleep(10*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/fkbaehtx.html