Reputation: 25
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)
}
Upvotes: 0
Views: 63
Reputation: 164
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
Upvotes: 0