Home >Backend Development >Golang >How to Check if a Go Channel is Closed Without Reading from It?
How to Check a Channel Is Closed without Reading It?
This question arises when working with channels in Go, where it is essential to determine channel closure without blocking. In the provided code example, it is desired to remove a channel from a slice when the corresponding worker exits.
The Problem
Closing a channel in worker() while trying to write to it in the controller() will cause a panic. Using a mutex to protect this operation leads to a deadlock. Assigning a larger buffer to the channel is not a viable solution either.
Proposed Solution
To resolve this issue, it is suggested that worker() closes the channel when it exits. The controller() can then check for closed channels and skip writing to them. However, there is currently no built-in function in Go to check channel closure without reading from it.
Possible Workarounds
The above is the detailed content of How to Check if a Go Channel is Closed Without Reading from It?. For more information, please follow other related articles on the PHP Chinese website!