1
2

More than 5 years have passed since last update.

golang 並列処理を動的に生成して同じ変数へ書き込む

Posted at

目的

  • 並列処理させたい処理(func) の動的生成
  • 並列処理部分だけを関数化

感想

  • chan使わなくてもできる
  • chanとの使い分けはよくわからない

コード

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
}


1
2
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2