I
I
idin2020-02-16 16:16:55
go
idin, 2020-02-16 16:16:55

Question about channels and blocking?

I'm trying to understand how Go works. and something does not reach
Why in this case the program is blocked.

func main() {
    intCh := make(chan int) 
    intCh <- 10      // функция main блокируется
    fmt.Println(<-intCh)
}


And if the channel has a buffer, then everything works to the end
func main() {
    intCh := make(chan int,100) 
    intCh <- 10      // функция main неблокируется
    fmt.Println(<-intCh)
}


But I didn't get the logic. After all, the channel must be blocked because someone must receive data from the groutin (in this case, the main main). Since we all run in main, the channel is blocked. But why is it not blocked in the second case. That is, the code reaches the groutina with a buffer, puts data there and that's it, since it never blocks with a buffer. Like this logic and all?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
U
uvelichitel, 2020-02-16
@Izy

A channel in Go is a queue of declared capacity (implemented by a ring buffer). If you do not take it from the queue, it clogs and blocks.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question