Explain the differences between go make of chan int 1 and make of chan int

  • 2020-09-16 07:30:32
  • OfStack

One problem encountered with golang channel: it was found that the go coroutine read channel data did not perform cooperatively as expected.

After investigation:

Improper use of channel resulted in channel being buffered and bufferless. Here is the difference between the two.

Buffer free channel

chan created with make(chan int) is bufferless. When send data reaches chan, it will block the running of the current coroutine without fetching the data. ch < - The following code will not run until the channel data is received and the current program will not proceed.


ch := make(chan int) //  Create bufferless channel

go func() {
  fmt.Println("time sleep 5 second...")
  time.Sleep(5 * time.Second)
  <-ch
}()
h
fmt.Println(" The block ...")
ch <-1  //  The coroutine will block, waiting for the data to be read 
fmt.Println("ch  Data is consumed and the master coroutine exits ")

There is a buffer channel

The buffer of channel is 1, the first data is sent to channel, and the main coroutine does not exit. On the second send, the buffer is full and the primary coroutine is blocked.


ch := make(chan int, 1) //  Create buffered channel
go func() {
  fmt.Println("time sleep 5 second...")
  time.Sleep(5 * time.Second)
  <-ch
}()
ch <-1  //  The coroutines do not block, waiting for the data to be read 
fmt.Println(" The first 2 Send data to channel .   The block ")
ch <-1  //  The first 2 Send data to channel,  Before the data is read, because the buffer is full,   So it will block the main coroutine. 
fmt.Println("ch  Data is consumed and the master coroutine exits ")

Summary: When creating channel, pay attention to whether buffers are needed. Buffered: No sender blocking occurs when the buffer size is not exceeded. Buffered: The sender is always blocked as long as the channel data is not taken away.


Related articles: