在某些情况下您需要关闭通道,而在某些情况下则不需要。http://play.golang.org/p/piJHpZ2-aUqueue := 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_Bjobs := 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)
1 回答
- 1 回答
- 0 关注
- 160 浏览
添加回答
举报
0/150
提交
取消