Created
March 23, 2024 20:32
-
-
Save x1unix/577be33524e770fe0a85c65af4070011 to your computer and use it in GitHub Desktop.
Go - check if a channel is closed without read
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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