Question

Why is there a deadlock even tho I just pass one and get one output from the channel?

package main

import "fmt"
import "math/cmplx"

func max(a []complex128, base int, ans chan float64,  index chan int) {

    fmt.Printf("called for %d,%d\n",len(a),base)

    maxi_i := 0
    maxi := cmplx.Abs(a[maxi_i]);

    for i:=1 ; i< len(a) ; i++ {
        if cmplx.Abs(a[i]) > maxi {
            maxi_i = i
            maxi = cmplx.Abs(a[i])
        }
    }

    fmt.Printf("called for %d,%d and found %f %d\n",len(a),base,maxi,base+maxi_i)

    ans <- maxi
    index <- base+maxi_i
}

func main() {
    ans := make([]complex128,128)

    numberOfSlices := 4
    incr := len(ans)/numberOfSlices
    tmp_val := make([]chan float64,numberOfSlices)
    tmp_index := make([]chan int,numberOfSlices)
    for i,j := 0 , 0; i < len(ans); j++{
        fmt.Printf("From %d to %d - %d\n",i,i+incr,len(ans))
        go max(ans[i:i+incr],i,tmp_val[j],tmp_index[j])

        i = i+ incr
    }
//After Here is it stops deadlock
    maximumFreq := <- tmp_index[0]
    maximumMax := <- tmp_val[0]
    for i := 1; i < numberOfSlices; i++ {

        tmpI := <- tmp_index[i]
        tmpV := <- tmp_val[i]

        if(tmpV > maximumMax ) {
            maximumMax = tmpV
            maximumFreq = tmpI
        }
    }

    fmt.Printf("Max freq = %d",maximumFreq)

}
Was it helpful?

Solution

For those reading this question and perhaps wondering why his code failed here's an explanation.

When he constructed his slice of channels like so:

tmp_val := make([]chan float64,numberOfSlices)

He made slice of channels where every index was to the channels zero value. A channels zero value is nil since channels are reference types and a nil channel blocks on send forever and since there is never anything in a nil channel it will also block on recieve forever. Thus you get a deadlock.

When footy changes his code to construct each channel individually using

tmp_val[i] = make(chan float64)

in a loop he constructs non-nil channels and everything is good.

OTHER TIPS

I was wrong in making of the chan. Should have done

numberOfSlices := 4
incr := len(ans)/numberOfSlices
var tmp_val [4]chan float64
var tmp_index [4]chan int

for i := range tmp_val {
    tmp_val[i] = make(chan float64)
    tmp_index[i] = make(chan int)
}

for i,j := 0 , 0; i < len(ans); j++{
    fmt.Printf("From %d to %d [j:%d] - %d\n",i,i+incr,j,len(ans))
    go maximumFunc(ans[i:i+incr],i,tmp_val[j],tmp_index[j])

    i = i+ incr
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top