A
A
Artem Rogozin2019-09-03 17:10:50
go
Artem Rogozin, 2019-09-03 17:10:50

Why do channels in go work so strangely?

package main
import "fmt"
  
func main() {
    fmt.Println("Start")
     // создание канала и получение из него данных
    fmt.Println(<-createChan(5)) // блокировка
    fmt.Println("End")
}
func createChan(n int) chan int{
    ch := make(chan int)    // создаем канал
    ch <- n      // отправляем данные в канал
    return ch   // возвращаем канал
}

1. Why does this code start working if the channel is made buffered?
2. And why the rule does not work on a buffered channel: "The data sender must be a separately launched goroutine."

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Pavlyuk, 2019-09-03
@syberianv

Everything is simple.
1. If the channel is without a buffer, then when reading from it, the program will block at this place until someone in another goroutine writes a value to this channel. Accordingly, the write operation will also block until someone wants to read from the pipe.
2. If the channel has a buffer and there is still space left in the buffer, then the write operation will not block, but will immediately return control. The read operation will also not block if there is any data in the buffer. If the buffer is full, then the recording will behave the same as in step 1. If the buffer is empty, then reading will behave the same as in n1.
In your program, a channel is created inside createChan and immediately written to it. This entry is being locked, waiting for someone to read from the channel. But reading from the channel will only happen when you exit the function, so the program stops forever.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question