channel之阻塞六

2020-03-17  本文已影响0人  anthonydan
//开启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)
}
上一篇下一篇

猜你喜欢

热点阅读