Home > Software design >  Goroutine is taking same time to execute my function as for loop
Goroutine is taking same time to execute my function as for loop

Time:09-28

I have a function to create Istio VirtualService objects. I am using goroutines to execute my function concurrently, starting 100 workers.

            var data map[string]string
            for _, data = range MapList {
                wg.Add(1)
                limit.Execute(func() {
                    go func(data map[string]string) {
                        defer wg.Done()
                        _,_ = m.createVirtualServices(ctx, data, namespace)
                    }(data)
                })
                wg.Wait()
            }

this takes exact same time to execute if I'd just loop over seMapList and execute my function.

Why?

CodePudding user response:

Because you are waiting for the goroutine to complete right after you start it. Try this instead:

            for _, data = range MapList {
                wg.Add(1)
                limit.Execute(func() {
                    go func(data map[string]string) {
                        defer wg.Done()
                        _,_ = m.createVirtualServices(ctx, data, namespace)
                    }(data)
                })
            }
            wg.Wait() // Wait for them after all goroutines are created
  • Related