Dead End in Go, two splits of work

I am a bit stuck in a dead end problem along the way.

This program takes an array of ints, a and splits it into two. He then takes these two parts in two different routines and summarizes all the elements. After that, he should send two results in the res channel. Then two res (now ch) should be added together and printed.

My problem: I tried to solve the deadlock problem by moving around functions a lot, but nothing helps. It works well with just one routine run.

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) } 
+4
source share
1 answer

You never close a channel, so there is no signal for range to exit. He will simply try to receive, but there is nothing left of the dispatch.

You will need some way for your Add() function to see when it ends, if it is the last, so that it can close() channel, or you could just decrease the counter instead of using range in the loop, so 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

+4
source

All Articles