美文网首页
gobyexample-closing-channels

gobyexample-closing-channels

作者: bocsoft | 来源:发表于2018-11-04 15:58 被阅读0次

    来源:https://github.com/xg-wang/gobyexample/tree/master/examples

    //_关闭_一个通道意味着不能再向这个通道发送值了。这个特性可以用来给这个通道的接收方法传达工作已经完成的信息
    package main
    
    import "fmt"
    
    func main() {
        jobs := make(chan int, 5)
        done := make(chan bool)
    
        go func() {
            for {
    
                //如果`jobs`已经关闭了,并且通道中的所有的值都已经接收完毕,
                //那么`more`的值将是`false`. 当我们完成所有的任务时,将使用
                //这个特性通过`done`通道去进行通知
                j, more := <-jobs
                if more {
                    fmt.Println("received job", j)
                } else {
                    fmt.Println("received all jobs")
                    done <- true
                    return
                }
            }
        }()
    
        for j := 1; j <= 3; j++ {
            jobs <- j
            fmt.Println("send job", j)
        }
    
        //当没有多余的任务给这个工作 Go 协程时,我们将`close`这个 `jobs`通道
        close(jobs)
        fmt.Println("sent all jobs")
    
        <-done
    }
    
    

    输出结果:

    received job 1
    send job 1
    send job 2
    send job 3
    sent all jobs
    received job 2
    received job 3
    received all jobs
    
    

    相关文章

      网友评论

          本文标题:gobyexample-closing-channels

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