简体   繁体   中英

Goroutine buffered channel deadlock

In the main goroutine, I'm getting a deadlock if I send values to channel exceeded the capacity, but if I'm sending in a different goroutine, there will be no deadlock, Why?

func main() {
    c := make(chan int, 2)
    for i := 0; i < 3; i++ {
        c <- i
    }
}

func main() {
    c := make(chan int, 2)
    go func() {
        for i := 0; i < 3; i++ {
            c <- i
        }
        close(c)
    }()
    time.Sleep(5 * time.Second)
}
func main() {
   c := make(chan int, 2)
   for i := 0; i < 3; i++ {
       // Blocking operation
       c <- i
   }
}
By default >>>sends<<< and receives block(!) until both the sender and receiver are ready

Checkout - https://gobyexample.com/channels

There are no receivers on your channel, main goroutine(= sender) is blocked

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