Reputation: 43
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)
}
Upvotes: 4
Views: 283
Reputation: 9336
You're never closing the channel so there's no signal for the range
to quit. It'll just keep on trying to receive, but there's nothing left that's sending.
You would either need to have some way for your Add()
function to see when it ends if it is the last one so that it can close()
the channel, or you could just decrement a counter instead of using range
in the loop so that you don't need to use close()
.
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
// counts the number of messages sent on the channel
count := 0
// run the loop while the count is less than the total number of routines
for count < 2 {
s := <-ch
sum = sum + s
count++ // Increment the count after a routine sends its value
}
fmt.Println(sum)
}
DEMO: http://play.golang.org/p/oHcrUStjmm
Upvotes: 4