dqwcdqs358367 2017-05-03 07:12
浏览 186
已采纳

为什么Go的频道可以关闭两次?

When I am do some go practices code, I encounter a problem that a channel can be closed twice like this:

// jobs.go

package main

import (
   "fmt"
)

func main() {
    fmt.Println("Hello, playground")
    jobs := make(chan int, 5)
    done := make(chan bool)

    go func() {
        for {
            j,more := <-jobs

            fmt.Println("receive close: ", j, more)
            done <- true   
        }
    }()

    close(jobs)
    <- done
}

Output:

~ go run jobs.go
Hello, playground
receive close:  0 false
receive close:  0 false

But when I close the channel twice manually, I got panic: close of closed channel.

Why the code above can receive close twice?

  • 写回答

3条回答 默认 最新

  • douju9272 2017-05-03 07:21
    关注

    A channel can only be closed once, attempting to close a closed channel panics.

    But receiving from a closed channel is not limited, receiving from a closed channel:

    A receive operation on a closed channel can always proceed immediately, yielding the element type's zero value after any previously sent values have been received.

    A Go app runs until its main goroutine runs (given "normal" circumstances), or from another point of view: a Go app terminates when its main goroutine terminates, that is, the main() function returns. It does not wait for other non-main goroutines to complete.

    You started a 2nd goroutine with an endless for loop, with no way of terminating. So that loop will keep going until the main() function –which runs in the concurrent, main goroutine– returns. Since the for loop first receives from jobs, it waits for the main goroutine to close it (this receive operation can only then proceed). Then the main goroutine wants to receive from done, so that waits until the 2nd goroutine sends a value on it. Then the main goroutine is "free" to terminate at any moment. Your 2nd goroutine running the loop may receive an additional value from jobs since it's closed, but the subsequent send on done will block as there are nobody receiving from it anymore (and it's unbuffered).

    Receiving from a channel until it's closed is normally done using for range, which exits if the channel is closed:

    for j := range jobs {
        fmt.Println("received: ", j)
        done <- true
    }
    

    Of course this would cause a deadlock in your case, as the loop body would never be reached as nobody sends anything on jobs, and so the loop would never enter its body to send a value on done which is what the main goroutine waits for.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据