Golang execute go routine in a loop
Oct 30, 2020
Does the following code output “Sum = 45”? The answer is NO.
package mainimport (
"fmt"
"sync"
)func ConcurrentSum(l int) int {
var wg sync.WaitGroup
c := make(chan int, l)
for i := 0; i < l; i++ {
wg.Add(1)
go func() {
c <- i
wg.Done()
}()
}
wg.Wait()
close(c)
return processResult(c)
}func processResult(c <-chan int) int {
total := 0
for n := range c {
total += n
}
return total
}func main() {
sum := ConcurrentSum(10);
//What is the output here?
fmt.Println("Sum = ", sum)
}
If you want to have an output of “Sum = 45”, you have to pass the loop variable into the go routine as a parameter as below.
package mainimport (
"fmt"
"sync"
)func ConcurrentSum(l int) int {
var wg sync.WaitGroup
c := make(chan int, l)
for i := 0; i < l; i++ {
wg.Add(1)
go func(n int) {
c <- n
wg.Done()
}(i)
}
wg.Wait()
close(c)
return processResult(c)
}func processResult(c <-chan int) int {
total := 0
for n := range c {
total += n
} return total
}func main() {
sum := ConcurrentSum(10);
//Output: Sum = 45
fmt.Println("Sum = ", sum)
}