Help us understand the problem. What is going on with this article?

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

More than 3 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
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  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
ユーザーは見つかりませんでした