在某些情況下您需要關(guān)閉通道,而在某些情況下則不需要。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!而此代碼的關(guān)閉是可選的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)
我怎么知道關(guān)閉是必要的?
慕田峪4524236
2021-07-03 06:01:12