0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[Go] 並列処理と非同期処理

Posted at

Goで並列処理。非同期処理を組み合わせた場合どう書く

使うもの

sync package (https://golang.org/pkg/sync/) ※ 非同期処理

go routine
※ 並列処理

コード

go
package main

import (
    "fmt"
    "sync"
    "time"
)

const (
    MAX_EXECUTION_COUNT = 10 // 実行回数
    CONCURRENT_COUNT = 5   // 同時実行数
)


func main() {
    fmt.Printf("Start : %s \n", time.Now())
    res := make(chan string, MAX_EXECUTION_COUNT)
    concurrent := make(chan string, CONCURRENT_COUNT)
    defer close(res)
    defer close(concurrent)

    var results []string
    var wg sync.WaitGroup
    wg.Add(MAX_EXECUTION_COUNT) // 非同期処理のカウンターをセット
    for i := 0; i < MAX_EXECUTION_COUNT; i++ {
        go func(res chan string, concurrent chan string, no int, wg *sync.WaitGroup) {
            defer wg.Done() // defer で waitGroupのカウンターを減少
            name := fmt.Sprintf("No. %d", no)

            concurrent <- fmt.Sprintf("%s execute %s", time.Now(), name) // 同時実行カウンターをアップ(makeで変数サイズを固定。待機する)
            time.Sleep( 5 * time.Second)
            fmt.Printf("%s wait 5seconds. \n", name)
            res <- fmt.Sprintf("%s response %s", time.Now(), name) // 結果に詰めていく
            <- concurrent // 同時実行カウンターの開放
        }(res, concurrent, i, &wg)
    }
    wg.Wait() // 非同期処理が終わるまで待つ

    for {
        results = append(results, <- res) // 一つづつ結果を別変数に
        if len(res) <= 0 {
            break
        }
    }

    fmt.Printf("End : %s \n", time.Now())
}
0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?