Last active
December 20, 2015 04:29
-
-
Save simeonwillbanks/6071652 to your computer and use it in GitHub Desktop.
Go by Example: Closing Channels
https://gobyexample.com/closing-channels
#golang
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
❯ go run closing-channels.go | |
sent job 1 | |
sent job 2 | |
sent job 3 | |
sent all jobs | |
received job 1 | |
received job 2 | |
received job 3 | |
received all jobs |
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" | |
) | |
func main() { | |
jobs := make(chan int, 5) | |
done := make(chan bool) | |
go func() { | |
for { | |
j, more := <-jobs | |
if more { | |
fmt.Println("received job", j) | |
} else { | |
fmt.Println("received all jobs") | |
done <- true | |
return | |
} | |
} | |
}() | |
for i := 1; i <= 3; i++ { | |
jobs <- i | |
fmt.Println("sent job", i) | |
} | |
close(jobs) | |
fmt.Println("sent all jobs") | |
<-done | |
} |
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
$ go run closing-channels.go | |
sent job 1 | |
received job 1 | |
sent job 2 | |
received job 2 | |
sent job 3 | |
received job 3 | |
sent all jobs | |
received all jobs |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment