简体   繁体   中英

go channel, seems all right, but it gets deadlock

package main
import "fmt"
import "time"

func main() {
     c := make(chan int)
     c <- 42    // write to a channel

     val := <-c // read from a channel
     println(val)
}

I think c <- 42 put 42 to channel c, then val := <-c put value in c to val. but why does it get deadlock?

You have created an unbuffered channel. So the statement c <- 42 will block until some other goroutine tries to receive a value from the channel. Since no other goroutine is around to do this, you got a deadlock. There are two ways you could fix this:

  1. Perform the receive in a different goroutine.
  2. Add a buffer to the channel. For example, c := make(chan int, 1) would allow you to send a single value on the channel without blocking.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM