Explain the difference between make (Chan int, 1) and make (Chan int) in go language

Time:2020-11-18

There is a problem with golang channel: it is found that the go coprocessor does not execute cooperatively as expected when reading channel data.

After checking the data:

Due to improper operation of channel, there are buffers and no buffers in channel. The following is the difference between them.

No buffer channel

Chan created with make (Chan int) has no buffer. When sending data to Chan, the running of the current coprocessor will be blocked when no coprocessor fetches the data. The code after Ch < – will not run again, and the current coprocessor will not continue to execute until the data of the channel is received.

Ch: = make (channel int) // create unbuffered channel

go func() {
  fmt.Println("time sleep 5 second...")
  time.Sleep(5 * time.Second)
  <-ch
}()
h
fmt.Println ("about to block..."
Ch < - 1 // the coprocessor will block and wait for the data to be read
fmt.Println (CH data is consumed and the main process exits)

With buffer channel

The first channel will not be sent to the first channel. The second time the buffer is full, the main coprocessor is blocked.

Ch: = make (channel int, 1) // create buffered channel
go func() {
  fmt.Println("time sleep 5 second...")
  time.Sleep(5 * time.Second)
  <-ch
}()
Ch < - 1 // the coprocessor will not block and wait for the data to be read
fmt.Println ("the second time the data is sent to the channel, it will be blocked")
Ch < - 1 // send data to the channel for the second time. Before the data is read, the main coprocessor will be blocked because the buffer is full.
fmt.Println (CH data is consumed and the main process exits)

Conclusion: when creating a channel, pay attention to whether a buffer is needed. When there is a buffer, the sender will not block if the buffer size is not exceeded. If there is no buffer, the sender will always be blocked as long as the channel data is not taken away.

The above is a detailed explanation of the differences between go language make (Chan int, 1) and make (Chan int), hoping to help you. If you have any questions, please leave me a message, and the editor will reply to you in time. Thank you very much for your support to the developeppaer website!
If you think this article is helpful to you, welcome to reprint, please indicate the source, thank you!

Recommended Today

Lua language novice simple tutorial

1、 Foreword Lua is a lightweight and compact scripting language, which is written in standard C language and open in the form of source code. Its design purpose is to be embedded in the application, so as to provide flexible expansion and customization functions for the application. Lua can be applied in game development, independent […]