Go channels and deadlock

后端 未结 3 824
情歌与酒
情歌与酒 2020-12-24 14:23

I\'m trying to understand the Go language. I tried to create two goroutines that chain the flow between them using two channels:

func main() {
c1 := make(cha         


        
3条回答
  •  孤城傲影
    2020-12-24 15:04

    Go channels created with make(chan int) are not buffered. If you want a buffered channel (that won't necessarily block), make it with make(chan int, 2) where 2 is the size of the channel.

    The thing about unbuffered channels is that they are also synchronous, so they always block on write as well as read.

    The reason it deadlocks is that your first goroutine is waiting for its c2 <- i to finish while the second one is waiting for c1 <- i to finish, because there was an extra thing in c1. The best way I've found to debug this sort of thing when it happens in real code is to look at what goroutines are blocked and think hard.

    You can also sidestep the problem by only using synchronous channels if they're really needed.

提交回复
热议问题