Home >Backend Development >Golang >How golang functions share data through pipes
Pipelines are a communication mechanism in the Go language for sharing data between Goroutines. A pipe can be created via the make(chan type) function, which has both read and write ends. The following example function shares data through a pipe, adds two numbers, and sends the result through a pipe: Creates two pipes, one for inputting the numbers and one for outputting the result. Start a Goroutine to run the addNumbers function. Send the number to the input pipe. Close the input pipe. Receives and prints the results from the output pipe.
Go functions use pipes to share data
Pipelines are a very important communication mechanism in the Go language and can be used in Sharing data between Goroutines. This article will introduce how to use pipes to share data in Go functions, with practical examples.
Pipe basics
Pipes are unbuffered or buffered queues used to transfer data between Goroutines. Pipes have read and write ends and can be created in different ways, most commonly using the make(chan type)
function.
Function Example
The following example function adds two numbers and sends the result through a pipe:
func addNumbers(input chan int, output chan int) { for { num1, ok := <-input if !ok { close(output) return } num2, ok := <-input if !ok { close(output) return } output <- num1 + num2 } }
Usage Example
To share data using this function, you can use the following code:
func main() { input := make(chan int) output := make(chan int) go addNumbers(input, output) input <- 10 input <- 20 close(input) result := <-output fmt.Printf("Result: %d\n", result) }
This code creates two pipes, one for input numbers and one for output results. It starts a Goroutine to execute the addNumbers
function and then sends two numbers to the input pipe. When the input pipe is closed, the function closes the output pipe, indicating completion. It then receives the result from the output pipe and prints it to the console.
Conclusion
Pipes in Go enable functions to easily share data. By using Goroutines, we can process data in parallel and improve the performance of our application.
The above is the detailed content of How golang functions share data through pipes. For more information, please follow other related articles on the PHP Chinese website!