Last active
May 10, 2017 20:57
-
-
Save jomoespe/2b6ae51e31a303fb73d561981943bcb8 to your computer and use it in GitHub Desktop.
Closing a channel
This file contains hidden or 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" | |
) | |
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