美文网首页
channel的关闭

channel的关闭

作者: 不死鸟F21 | 来源:发表于2020-01-07 21:28 被阅读0次

    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()
    
    }
    

    相关文章

      网友评论

          本文标题:channel的关闭

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