How to set the Go channel buffer
This article mainly introduces the relevant knowledge of "how to set the Go channel buffer." Xiao Bian shows you the operation process through actual cases. The operation method is simple, fast and practical. I hope this article "how to set the Go channel buffer" can help you solve the problem.
channel buffer
The channel can set the buffer, and the buffer size is specified by the second parameter of make:
ch := make(chan int, 100)
Buffered channels allow data transmission at the sender and data acquisition at the receiver to be asynchronous, that is, the data sent by the sender can be placed in the buffer and can wait for the receiver to acquire the data, rather than requiring the receiver to acquire the data immediately.
However, since the size of the buffer is limited, there must be a receiver to receive data, otherwise the buffer will be full and the data sender will not be able to send data.
Note: If the channel is unbuffered, the sender blocks until the receiver receives a value from the channel. If the channel is buffered, the sender blocks until the value sent is copied into the buffer; if the buffer is full, it means waiting until a receiver gets a value. The receiver blocks until it has a value to receive.
examples
package main
import "fmt"
func main() {
//Here we define a buffered channel that can store integer types
//buffer size is 2
ch := make(chan int, 2)
//since ch is a buffered channel, we can send two data at the same time
//instead of having to synchronize the read data immediately
ch