channel的关闭

2020-01-07  本文已影响0人  不死鸟F21

1.生产者和消费者

package main

import (
    "fmt"
    "sync"
)

func dataProducer(ch chan<- int, wg *sync.WaitGroup) {
    go func() {
        for i := 0; i < 10; i++ {
            ch <- i
        }
        wg.Done()
    }()
}

func dataReceiver(ch <-chan int, wg *sync.WaitGroup) {
    go func() {
        for i := 0; i < 10; i++ {
            data := <-ch
            fmt.Println(data)
        }
        wg.Done()
    }()
}

func main() {
    var wg sync.WaitGroup
    ch := make(chan int)
    wg.Add(1)
    dataProducer(ch, &wg)
    wg.Add(1)
    dataReceiver(ch, &wg)
    wg.Wait()

}

2.关闭channel

package main

import (
    "fmt"
    "sync"
)

func dataProducer(ch chan<- int, wg *sync.WaitGroup) {
    go func() {
        for i := 0; i < 10; i++ {
            ch <- i
        }
        //数据产生完毕,关闭channel
        close(ch)
        fmt.Println("close channel...")
        wg.Done()
    }()
}

func dataReceiver(ch <-chan int, wg *sync.WaitGroup) {
    go func() {
        for {
            if data, ok := <-ch; ok {
                fmt.Println(data)
            } else {
                break
            }

        }
        wg.Done()
    }()
}

func main() {
    var wg sync.WaitGroup
    ch := make(chan int)
    wg.Add(1)
    dataProducer(ch, &wg)
    wg.Add(1)
    dataReceiver(ch, &wg)
    wg.Wait()

}
上一篇下一篇

猜你喜欢

热点阅读