Skip to content

Instantly share code, notes, and snippets.

@x1unix
Created March 23, 2024 20:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save x1unix/577be33524e770fe0a85c65af4070011 to your computer and use it in GitHub Desktop.
Save x1unix/577be33524e770fe0a85c65af4070011 to your computer and use it in GitHub Desktop.
Go - check if a channel is closed without read
package main
import (
"fmt"
"unsafe"
)
// Copy of hchan struct with first necessary fields.
// See: "src/runtime/chan.go"
type hchan struct {
qcount uint // total data in the queue
dataqsiz uint // size of the circular queue
buf unsafe.Pointer // points to an array of dataqsiz elements
elemsize uint16
closed uint32
}
// IsClosed checks whether a passed channel is closed.
//
// Warning: possible race conditions ahead as it doesn't respect inner semaphore.
func IsClosed[T any](ch chan T) bool {
sChan := (*hchan)(unsafe.Pointer(*(*unsafe.Pointer)(unsafe.Pointer(&ch))))
return sChan.closed != 0
}
func main() {
ch := make(chan int, 2)
fmt.Println("IsClosed:", IsClosed(ch))
close(ch)
fmt.Println("IsClosed:", IsClosed(ch))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment