Skip to content

Instantly share code, notes, and snippets.

@taka011239
Last active August 29, 2015 14:00
Show Gist options
  • Save taka011239/11529137 to your computer and use it in GitHub Desktop.
Save taka011239/11529137 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"sync"
)
func main() {
ch := make(chan int)
var wg sync.WaitGroup
go func() {
wg.Add(1)
defer wg.Done()
for {
v, ok := <-ch
if !ok {
fmt.Println("channel is closed!")
break
}
fmt.Println(v)
}
}()
for i := 0; i < 5; i++ {
ch <- i
}
close(ch)
wg.Wait()
}
package main
import (
"fmt"
"sync"
)
func main() {
ch := make(chan int)
var wg sync.WaitGroup
go func() {
wg.Add(1)
defer wg.Done()
for v := range ch {
fmt.Println(v)
}
}()
for i := 0; i < 5; i++ {
ch <- i
}
close(ch)
wg.Wait()
}
@taka011239
Copy link
Author

rangeでchannelをreadしている場合、closeで列挙が終了する

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment