Go channels and deadlock

帅比萌擦擦* 提交于 2019-11-30 00:34:19

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.

nmichaels is right on with his answer, but I thought I'd add that there are ways to figure out where you're deadlocking when debugging a problem like this.

A simple one is if you're on a Unix-like OS, run the command

kill -6 [pid]

This will kill the program and give a stack trace for each goroutine.

A slightly more involved way is to attach gdb.

gdb [executable name] [pid]

You can examine the stack and variables of the active goroutine as normal, but there's no easy way to switch goroutines that I know of. You can switch OS threads in the usual way, but that might not be enough to help.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!