A problem encountered with golang channel: I found that the go coroutine read channel data and did not perform collaboratively as expected.
After searching the information:
Inappropriate operation using channel causes channel to be divided into buffers and unbuffered channels. The following is the difference between the two.
No buffer channel
The chan created with make(chan int) is bufferless. When sending data to chan, the current coroutine will block the run of the current coroutine if no coroutine fetches data. ch <- The subsequent code will not run again, and the current coroutine will not continue to execute until the channel data is received.
ch := make(chan int) // Create unbuffered channel go func() { ("time sleep 5 second...") (5 * ) <-ch }() h ("It's about to block...") ch <-1 // The coroutine will block, waiting for the data to be read("Ch data is consumed, the main coroutine exits")
There is a buffer channel
The buffer of channel is 1. The first data is sent to the channel, and the main coroutine will not exit. When the second time is sent, the buffer is full, and the main coroutine is blocked.
ch := make(chan int, 1) // Create buffered channelgo func() { ("time sleep 5 second...") (5 * ) <-ch }() ch <-1 // The coroutine will not block and wait for the data to be read("The second time the data is sent to the channel, it will be blocked") ch <-1 // The second time the data is sent to the channel, before the data is read, the main coroutine will be blocked because the buffer is full.("Ch data is consumed, the main coroutine exits")
Summary: When creating a channel, be careful whether the buffer is needed. When there is a buffer: When the buffer size does not exceed, the sender will not block. When there is no buffer: As long as the channel data is not taken away, the sender will always be blocked.
The above is a detailed explanation of the difference between go language make(chan int, 1) and make (chan int) introduced to you by the editor. I hope it will be helpful to 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 for my website!
If you think this article is helpful to you, please reprint it. Please indicate the source, thank you!