On Thu, Nov 12, 2020 at 6:19 PM 陶青云 <qingyu...@gmail.com> wrote: > > ``` > // c is buffered channel > select { > case c <- result: > default: > // full, drop old one > <-c > c <- result > } > ``` > > I have a code like this, but there may be a race condition in the default > case. I enconter a > deadlock that the goroutine block on 'c<'.
A channel normally communicates from one goroutine to another. It doesn't make much sense for a single goroutine to both send and receive on the same channel, unless there is some protocol that specifies when the goroutine should switch from sending to receiving. Code like you show above is inherently racy. When the select starts, the channel might be full, so the select chooses the default case. Immediately after the select chooses the default case, but before it runs the channel receive operation, other goroutines might receive all the values from the channel. Then, the receive on the original channel will start, but there is nothing left on the channel, so it will hang. The way to avoid this kind of race is for a goroutine to always either send or receive on a channel, never both. Ian -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/CAOyqgcWDyMLTQrv%2Bsjs%2BH0%2BRsrYfNF_nWKRM%2B7MnKJuKz7tEPg%40mail.gmail.com.