Skip to content

Instantly share code, notes, and snippets.

@zgiber
Created September 2, 2015 08:55
Show Gist options
  • Save zgiber/49125f57a02f27afb6b5 to your computer and use it in GitHub Desktop.
Save zgiber/49125f57a02f27afb6b5 to your computer and use it in GitHub Desktop.
Handling closed channels.
package main
import (
"fmt"
"time"
)
func main() {
c := make(chan string)
go process(c)
select {
case b := <-c:
fmt.Println(b)
}
close(c)
go process(c)
for {
select {
case b, ok := <-c:
if ok {
fmt.Println(b)
} else {
time.Sleep(100 * time.Millisecond)
fmt.Println("time to say goodbye")
return
}
}
}
}
func process(c chan string) {
defer func() {
if r := recover(); r != nil {
fmt.Println("channel closed")
}
}()
c <- "hello"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment