Created
September 2, 2015 08:55
-
-
Save zgiber/49125f57a02f27afb6b5 to your computer and use it in GitHub Desktop.
Handling closed channels.
This file contains 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" | |
"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