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