0

I need limit running function by maxTasks variable. Can you check my answer and possible to make adjustments.

package main

import (
    "fmt"
    "math/rand"
    "time"
)

func main() {
    maxTasks := 10
    var tasks []func()
    for x := 0; x < 50; x++ {
        fmt.Println("add new task with num ", x)
        tasks = append(tasks, func(x int) func() {
            fmt.Println("create function with ", x)
            return func() {
                worktime := rand.Intn(10)
                time.Sleep(time.Duration(worktime) * time.Second)
                fmt.Println("current task:",x )
                fmt.Println(" with worktime ",worktime)
            }
        }(x))
    }
    //tasks[0]()
    ch := make(chan int, maxTasks)
    for _, task := range tasks {

        go func(t func()) {
            ch <- 1
            t()
            fmt.Println("current task:",len(ch))
            <- ch
        }(task)
    }
    time.Sleep(10000 * time.Second)
}
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
0xdeface
  • 23
  • 5
  • There's no question here. What you do expect, and what do you get? – Marc Jun 24 '20 at 06:46
  • i expect than in the same time will be running only 10 functions – 0xdeface Jun 24 '20 at 06:50
  • 1
    There is nothing to limit the number of goroutines being created. They'll launch as quickly as possible, then some will wait until they can send `1` to the channel. You haven't shown what isn't working. – Marc Jun 24 '20 at 06:55
  • If you want to have "only 10 goroutines active at any time" you may want to use a goroutine pool: https://gobyexample.com/worker-pools – phonaputer Jun 24 '20 at 07:00
  • you should search with keywords like https://stackoverflow.com/search?q=%5Bgo%5D+pool+worker –  Jun 24 '20 at 07:02
  • The whole approach here is flawed. Try splitting the task into smaller parts. Create one goroutine that keeps track of the number of tasks, and starts new one when the amount is lower then maxTasks. – super Jun 24 '20 at 07:25
  • Why approach here is flawed? This icode work correctly. Can you write code and share on go playground – 0xdeface Jun 24 '20 at 07:30
  • @Marc they will wait and my jobs will be not running. is it limiting, right? Or will be better limit goroutines (not a task function)? – 0xdeface Jun 24 '20 at 07:33
  • 1
    I think this previous question is the same: https://stackoverflow.com/questions/25306073/always-have-x-number-of-goroutines-running-at-any-time – Andrew W. Phillips Jun 24 '20 at 08:06

0 Answers0