I'm a bit stuck on a deadlock issue in go.
This program takes an array of ints, a, and splits it into two. Then it takes these two parts in two different routines and sum up all elements. After this, it's supposed to send the two results in the channel res. The two res (now ch) then should be added together and print.
My problem: I've tried to tackle the deadlock problem by moving about close-functions a lot, but nothing seems to help. It works well with only one routine Add running obviously.
package main
import (
"fmt"
)
// Add adds the numbers in a and sends the result on res.
func Add(a []int, res chan<- int) {
sum := 0
for i := range a {
sum = sum + a[i]
}
res <- sum
}
func main() {
a := []int{1, 2, 3, 4, 5, 6, 7}
n := len(a)
ch := make(chan int)
go Add(a[:n/2], ch)
go Add(a[n/2:], ch)
sum := 0
for s := range ch {
sum = sum + s
}
//close(ch)
fmt.Println(sum)
}