james-l
2/26/2017 - 3:00 AM

go通道的关闭 close chan

go通道的关闭 close chan

import "time"
import "fmt"

func main() {

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

	go func() {
		for {
			j, more := <-jobs
			if more {
				fmt.Println("recevied job", j)
				time.Sleep(time.Second * 3)
			} else {
				fmt.Println("received all jobs")
				done <- true
				return
			}
		}
	}()

	for j := 1; j <= 3; j++ {

		time.Sleep(time.Second * 2)
		fmt.Println("send job", j)
		jobs <- j
	}
	close(jobs)

	fmt.Println("send all jobs")
	<-done
}