package main
import (
"math/rand"
"sync"
"time"
)
type result struct {
param int
waitTime int
}
// 並列処理の結果入れる箱
var results = []*result{}
func main() {
funcSize := randomInt()
println("func size:", funcSize)
//並列処理したいfuncの生成
functions := createFunctions(funcSize)
//並列処理
goRoutine(functions)
//結果確認
println("result ############")
waitSum := 0
paramSum := 0
for index, result := range results {
println("index:", index, "waitTime:", result.waitTime, "param:", result.param)
waitSum += result.waitTime
paramSum += result.param
}
println("result size:", len(results), "wait sum:", waitSum, "param sum:", paramSum)
}
func randomInt() int {
rand.Seed(time.Now().UnixNano())
return rand.Intn(10)
}
func createFunctions(num int) (functions []func()) {
for i := 0; i < num; i++ {
functions = append(functions, createFunctionBase())
}
return functions
}
func createFunctionBase() func() {
return func() {
waitTime := randomInt()
paramInt := randomInt()
println("sleep ", waitTime, " started.")
time.Sleep(time.Duration(waitTime) * time.Second)
println("sleep ", waitTime, " finished.")
results = append(results, &result{param: paramInt, waitTime: waitTime})
}
}
func goRoutine(funcList []func()) error {
println("started.")
var waitGroup sync.WaitGroup
// 関数の数だけ並行化する
for _, function := range funcList {
waitGroup.Add(1) // 待つ数をインクリメント
// Goルーチンに入る
go func(f func()) {
defer waitGroup.Done() // 待つ数をデクリメント
f()
}(function)
}
waitGroup.Wait() // 待つ数がゼロになるまで処理をブロックする
println("all finished.")
return nil
}