How to check a channel is closed or not without reading it?

前端 未结 8 897
别跟我提以往
别跟我提以往 2020-12-12 14:56

This is a good example of workers & controller mode in Go written by @Jimt, in answer to \"Is there some elegant way to pause & resume any other goroutine in golang?

8条回答
  •  既然无缘
    2020-12-12 15:16

    In a hacky way it can be done for channels which one attempts to write to by recovering the raised panic. But you cannot check if a read channel is closed without reading from it.

    Either you will

    • eventually read the "true" value from it (v <- c)
    • read the "true" value and 'not closed' indicator (v, ok <- c)
    • read a zero value and the 'closed' indicator (v, ok <- c)
    • will block in the channel read forever (v <- c)

    Only the last one technically doesn't read from the channel, but that's of little use.

提交回复
热议问题