I cannot use channel

I used channel like this in func main

d := make(chan int)
d <- 2
It failed

fatal error: all goroutines are asleep - deadlock!

goroutine 1 [chan send]:
but I find some code like this :

package main

import “fmt”

func sum(a []int, c chan int) {
total := 0
for _, v := range a {
total += v
}
c <- total // send total to c
}

func main() {
a := []int{7, 2, 8, -9, 4, 0}

c := make(chan int)
go sum(a[:len(a)/2], c)
go sum(a[len(a)/2:], c)
x, y := <-c, <-c  // receive from c

fmt.Println(x, y, x + y)

}
This code can work well ,

Why ?

If you make a channel via make(chan int) it doesn’t have any buffer. That means that when you go to write to it from one goroutine, there needs to be another available to read from it.

The reason the second piece of code works is because the producers (things writing to the channel) are both doing so in separate goroutines, so they don’t block the main thread which can continue and eventually read the values. In your example the entire main thread gets blocked because it can’t write to the channel and there aren’t any other goroutines running that can do anything to help.

One way to fix this is to create a buffer for your channel. This will all you to write as many elements as your buffer size is without blocking. eg - https://play.golang.org/p/UznRCBUvco

That isn’t very useful though since you likely want to use goroutines if you are using channels, so you probably want to make your producers work in a goroutine to fix your issue. You can see an example of that here: https://play.golang.org/p/ODa79Qq1aj (or below)

package main

import (
	"fmt"
)

func main() {
	ch := make(chan int)
	go func() {
		ch <- 123
	}()
	fmt.Println(<-ch)
}
2 Likes

Thanke

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.