Skip to content

Instantly share code, notes, and snippets.

@iamatypeofwalrus
Created December 11, 2014 19:31
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save iamatypeofwalrus/84b6c7d946a6a4143a1d to your computer and use it in GitHub Desktop.
Save iamatypeofwalrus/84b6c7d946a6a4143a1d to your computer and use it in GitHub Desktop.
Check if a Go Channel is open or closed
// An intersting pattern for testing, but you can use the check anywhere
import "testing"
func TestCheckingChannel(t *testing.T) {
stop := make(chan bool)
// Testing some fucntion that SHOULD close the channel
func (stop chan bool) {
close(chan)
}(stop)
// Make sure that the function does close the channel
_, ok := (<-stop)
// If we can recieve on the channel then it is NOT closed
if ok {
t.Error("Channel is not closed")
}
}
@bagardavidyanisntreal
Copy link

@noamnelke
Copy link

I have to admit that I didn't understand all of your code in the playground, but it seems more complex and slower. It also doesn't do what the original intent of this gist is: which I interpret as reading from a channel in a non-blocking way.

General remark: I don't think it's a good idea to overload the built-in close function (the only way to close a channel).

@bagardavidyanisntreal
Copy link

@noamnelke I have never heard about overload in Go. the close func in this gist is just a Closer implementation

I didn't understand all of your code

so sad

@mrtdeh
Copy link

mrtdeh commented Jan 30, 2024

The error will never occur. If the channel isn't closed the function will block forever on line 13.

It would work if you replaced line 13 with the following:

	ok := true
	select {
	case _, ok = <-stop:
	default:
	}

A select with a default clause is a non-blocking read from the channel.

POC on Go Playground

Thanks , you save my day.

@noamnelke
Copy link

❤️

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment