Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

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

More than 5 years have passed since last update.

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

na-o-ys
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away