猿问

我怎么知道关闭是必要的?

在某些情况下您需要关闭通道,而在某些情况下则不需要。


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)


慕田峪4524236
浏览 161回答 1
1回答
随时随地看视频慕课网APP

相关分类

Go
我要回答