LoginSignup
15
19

More than 5 years have passed since last update.

Goroutine の同時実行数を制限する

Posted at

Goroutine の同時実行数を制限します。

やりかた

下の例では、10 個のタスク (do_something) が 2 個ずつ並列実行されます。

// num 個のワーカーを生成し、tasks チャンネルを監視させる
func GenWorkers(num int) chan<- func() {
    tasks := make(chan func())
    for i := 0; i < num; i++ {
        go func() {
            for f := range tasks {
                f()
            }
        }()
    }
    return tasks
}

func main() {
    // 2 個ずつ実行するワーカー
    tasks := GenWorkers(2)

    // 10 個のタスクを渡す
    for i := 0; i < 10; i++ {
        tasks <- func() {
            do_something()
        }
    }
    return
}

参考

How would you define a pool of goroutines to be executed at once in Golang? - Stack Overflow

15
19
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
15
19