Closing Channels

来源:互联网 发布:ios6不越狱安装软件 编辑:程序博客网 时间:2024/05/16 17:55
packagemain
import "fmt"
func main() {
    jobs := make(chan int, 5)
    done := make(chan bool)
    go func() {
        for {
            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("sent job", j)
    }
    // 关闭通道
    close(jobs)
    fmt.Println("sent all jobs")
    <-done
}
                                             
0 0
原创粉丝点击