Buffered channels are an effective way to safely transfer data in concurrent programming of Go functions. They create a fixed-size buffer to store data to be sent or received. Use make to create a buffer channel and specify the capacity. Producer goroutines use chan
Usage of buffer channel in concurrent programming of Go language functions
Buffer channel is very useful in concurrent programming of Go language functions. It Allows safe passing of data between goroutines. It does this by creating a fixed-size buffer that stores the data to be sent or received.
Create buffer channel
bufferedChannel := make(chan int, 10)
The 10
here represents the capacity of the buffer, which can store up to 10 integers.
Communication between goroutines
Producer goroutine can use the chan<-
operator to send data to the channel:
go func() { bufferedChannel <- 42 }()
Consumer goroutine can use the <-chan
operator to receive data from the channel:
go func() { fmt.Println(<-bufferedChannel) }()
Practical case
To demonstrate the usage of buffered channels, Let us write a simple program that generates random numbers from the producer goroutine and passes it to the consumer goroutine for printing.
The code is as follows:
package main import ( "fmt" "math/rand" "sync" ) func main() { // 创建一个缓冲通道 bufferedChannel := make(chan int, 10) // 生成随机数的 goroutine go func() { for i := 0; i < 100; i++ { bufferedChannel <- rand.Intn(100) } close(bufferedChannel) // 发送完成后关闭通道 }() // 打印随机数的 goroutine var wg sync.WaitGroup wg.Add(1) go func() { defer wg.Done() for { value, ok := <-bufferedChannel if !ok { return // 通道已关闭 } fmt.Println(value) } }() wg.Wait() // 等待消费者 goroutine 结束 }
In this example, we set the capacity of the buffer to 10, which means that the producer goroutine can generate 10 random numbers in parallel , without blocking. The consumer goroutine loops receiving random numbers from the channel until the channel is closed.
The above is the detailed content of How to use buffer channels in Golang function concurrent programming. For more information, please follow other related articles on the PHP Chinese website!