商君

导航

Go Example--关闭通道

package main

import (
	"fmt"
)

func main() {
	jobs := make(chan int, 5)
	done := make(chan bool)

	go func() {
		for {
			//读取通道方式, val,ok := <-chan 通道关闭后,ok是false
			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
}

posted on 2018-10-19 16:19  漫步者01  阅读(169)  评论(0编辑  收藏  举报