Last active
August 29, 2015 14:00
-
-
Save taka011239/11529137 to your computer and use it in GitHub Desktop.
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" | |
"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() | |
} |
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" | |
"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() | |
} |
rangeでchannelをreadしている場合、closeで列挙が終了する
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
channelはcloseしてあげないと、readでデッドロックしてしまう