Skip to content

Instantly share code, notes, and snippets.

@simeonwillbanks
Last active December 20, 2015 04:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save simeonwillbanks/6071652 to your computer and use it in GitHub Desktop.
Save simeonwillbanks/6071652 to your computer and use it in GitHub Desktop.
Go by Example: Closing Channels https://gobyexample.com/closing-channels #golang
❯ 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
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
}
$ 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