Skip to content

Instantly share code, notes, and snippets.

@jomoespe
Last active May 10, 2017 20:57
Show Gist options
  • Save jomoespe/2b6ae51e31a303fb73d561981943bcb8 to your computer and use it in GitHub Desktop.
Save jomoespe/2b6ae51e31a303fb73d561981943bcb8 to your computer and use it in GitHub Desktop.
Closing a channel
package main
import (
"fmt"
"time"
)
const (
iterations = 5
sleepTime = 500 * time.Millisecond
)
func main() {
channel := make(chan int)
go doIt(channel)
for {
i, closed := <-channel // get channel and if it's closed
if !closed {
break
}
fmt.Printf("iteration = %d\n", i)
}
}
func doIt(channel chan int) {
for i := 0; i < iterations; i++ {
channel <- i
time.Sleep(sleepTime)
}
close(channel) // close the channel
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment