Created
September 4, 2018 12:58
-
-
Save paperlefthand/55c8147d5ebe7a243e9f65191be1d282 to your computer and use it in GitHub Desktop.
並行で発行したgoroutineをまとめ上げる処理
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() { | |
wg := &sync.WaitGroup{} | |
c := make(chan int, 10) | |
for i := 0; i < 10; i++ { | |
// goroutine発行前にAddすることで取り逃がしを防ぐ | |
wg.Add(1) | |
go func(c chan int, a int) { | |
c <- 2 * a | |
wg.Done() | |
}(c, i) | |
} | |
wg.Wait() | |
// closeしないと`range c`がいつまでも入力を待ち続けてしまう | |
close(c) | |
var nums []int | |
for n := range c { | |
nums = append(nums, n) | |
} | |
fmt.Println(nums) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment