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.

Golang ゴールーチンで並列数を指定して実行

Posted at
package main

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

func sub(message string) {
    fmt.Printf("%s start\n", message)
    time.Sleep(5 * time.Second)
    fmt.Printf("  -> %s end\n", message)
    time.Sleep(1 * time.Second)
}

func getMessages() (messages []string) {
  messages = []string{
    "a",
    "b",
    "c",
    "d",
    "e",
    "f",
    "g",
    "h",
  }
  return
}

func main() {
    // 並列数
    concurrency := 4
    // 並列キューを作成
    limit := make(chan int, concurrency)
    // WaitGroup 作成
    var wg sync.WaitGroup
    for _, message := range getMessages() {
        // WaitGroup のカウンタを上げる
        wg.Add(1)
        // 並列処理開始
        go func(message string, wg *sync.WaitGroup, limit chan int) {
            // WaitGroup のカウンタを下げる
            defer wg.Done()
            // 並列キューに値1を入れる
            limit <- 1
            // 並列処理させたい関数を実行
            sub(message)
            // 並列キューから値を取得する (<-limit)
            fmt.Printf(" (%d <-limit)\n", <-limit)
            time.Sleep(2 * time.Second)
        }(message, &wg, limit)
    }
    // WaitGroup のカウンタが0になるまで待つ
    wg.Wait()
}

実行結果

h start
d start
a start
b start
  -> b end
  -> a end
  -> d end
  -> h end
 (1 <-limit)
 (1 <-limit)
 (1 <-limit)
 (1 <-limit)
g start
c start
e start
f start
  -> c end
  -> f end
  -> e end
  -> g end
 (1 <-limit)
 (1 <-limit)
 (1 <-limit)
 (1 <-limit)
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?