There are two modes of using pipes to communicate between functions in the Go language: producer-consumer mode: the producer function writes to the pipe, and the consumer function reads the pipe. Work pool pattern: One function creates a work pipeline, and other functions receive work from the pipeline and execute it.
The communication mode between function and pipe in Go language
Pipeline is an effective mechanism for concurrent communication in Go language . A pipe is a buffered queue of elements that can be written to one end of the pipe and read from the other end. In this process, pipes can be used to synchronize execution and pass data between functions.
1. Pipe sending and receiving
The pipe can be initialized as an int channel, which can hold any number of ints.make
Function is used to create a pipeline:
numbers := make(chan int)
You can send values to the pipeline in the coroutine, usechan <-
:
go func() { numbers <- 42 close(numbers) }()
You can use<-chan
to read values from the pipe:
var num int num = <-numbers
close
The function is used to close the pipe, indicating that no more data will be written to the pipe:
close(numbers)
2. Buffered Pipes
Pipes can be unbuffered, which means that at most one element can be saved in the pipe. When the pipe is full, write operations are blocked. A buffered pipe can be created by specifying the second parameterbufferSize
:
numbers := make(chan int, 10)
Now the pipe can hold up to 10 elements, and writes will not block until the buffer fills up.
3. Modes of communication between functions and pipelines
There are two common modes of communication between functions and pipelines:
4. Practical Case: Producer-Consumer Pattern
The following is a simple example showing how to use pipelines between functions to achieve production Producer-Consumer Pattern:
package main import ( "fmt" "sync" ) func producer(ch chan int) { for i := 0; i < 10; i++ { ch <- i } close(ch) } func consumer(ch chan int, wg *sync.WaitGroup) { for num := range ch { fmt.Println(num) } wg.Done() } func main() { ch := make(chan int) var wg sync.WaitGroup wg.Add(1) go producer(ch) go consumer(ch, &wg) wg.Wait() }
In this example, theproducer
function writes 10 integers into the pipe and then closes the pipe.consumer
The function will read the integer from the pipe and print it out. In order to ensure that theconsumer
function does not exit before theproducer
function is completed,sync.WaitGroup
is used for synchronization.
The above is the detailed content of Pattern of communication between golang functions and pipelines. For more information, please follow other related articles on the PHP Chinese website!