14159
14159

Reputation: 185

go-routines and channels in go

I'm trying to run a few calculations in parallel using Go's concurrency:

func intensity_calc(input Matrix, distance float64) Matrix {
    output := create_matrix(len(input), len(input[0]))
    var wg sync.WaitGroup
    reverse := len(input)

    wg.Add(len(input) / 2)
    for i := 0; i < len(input)/2; i++ {
        output[i][x_ln] = input[i][x_ln]
        go func() { // creates a go-routine
        points <- contributions_sum(input, distance, input[i][x_ln])
        output[i][y_ln] = <-points
        output[reverse][y_ln] = output[i][y_ln]
        fmt.Println(i)
        defer wg.Done() // process is done
    }()
    }
    wg.Wait() // wait until all processes are finished
    return output
}

* output is a 2D array

the code supposes to take values from the array input send them to a function that returns the values into the channel points. the channel is defined globally:

 var points chan float64

and in the main() function:

 points = make(chan float64)

but I keep getting this error:

goroutine 2017 [chan send]:
main.intensity_calc.func1(0xc04206a000, 0xfa1, 0xfa1, 0x3f50624dd2f1a9fc, 0xc0420bb660, 0xc042094000, 0xfa1, 0xfa1, 0xfa1, 0xc0420bb650)
     C:/.../go concurrent calculation.go:71 +0xbf
created by main.intensity_calc
     C:/.../go concurrent calculation.go:76 +0x1c0

Upvotes: 0

Views: 225

Answers (1)

Matteo
Matteo

Reputation: 184

The instruction

var points = make(chan float64)

creates an unbuffered channel, which in turn means that

points <- contributions_sum(input, distance, input[i][x_ln])

will block until another go-routine reads from points.

Considering that all the go-routines in the code you posted perform a send on the channel before reading from it, they will all block waiting for a read on the same channel that will never happen (unless this is done in the code you didn't post, which you should have). As a result, you have a deadlock (which is usually written, is the error you quoted everything the console displays?).

Upvotes: 2

Related Questions