在某些情况下您需要关闭频道,而在某些情况下则不需要。
http://play.golang.org/p/piJHpZ2-aU
queue := make(chan string, 2)
queue <- "one"
queue <- "two"
close(queue)
for elem := range queue {
fmt.Println(elem)
}
我在这里
fatal error: all goroutines are asleep - deadlock!
而此代码的关闭是可选的
http://play.golang.org/p/Os4T_rq0_B
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
// close(done)