This article gives an example of how Golang determines whether Chan channel is closed. Share to everyone for your reference, specific as follows:
A friend in the group asked how to tell if Chan was closed because the channel of close does not block and returns the nil value of the type, resulting in a dead loop. Write an example here to record and share
If you don't judge whether Chan is closed
Notice: The following code produces a dead loop
Copy Code code as follows:
Package Main
Import (
"FMT"
)
Func Main () {
c: = make (chan int, 10)
C <-1
C <-2
C <-3
Close (c)
for {
Fmt. Println (<-C)
}
}
Judge whether Short Chan is closed
Copy Code code as follows:
Package Main
Import (
"FMT"
)
Func Main () {
c: = make (chan int, 10)
C <-1
C <-2
C <-3
Close (c)
for {
I, Isclose: = <-c
If!isclose {
Fmt. Println ("Channel closed!")
Break
}
Fmt. Println (i)
}
}
I hope this article will help you with your go language program.