SoFunction
Updated on 2025-03-03

Example of pipeline channel usage of Go language

This article describes the usage of pipeline Channel in Go language. Share it for your reference. The specific analysis is as follows:

channel is a pipe of type, and it can be sent or received by the channel operator <- .
ch <- v // Send v to channel ch.
v := <-ch // Receive from ch and assign to v.
(The "arrow" is the direction of the data flow.)
Like map and slice, the channel must be created before use:
ch := make(chan int)
By default, both sending and receiving are blocked until the other end is ready. This allows goroutine to be synchronized without explicit locks or race variables.

Copy the codeThe code is as follows:
package main
import "fmt"
func sum(a []int, c chan int) {
    sum := 0
    for _, v := range a {
        sum += v
    }
    c <- sum  // send sum to c
}
func main() {
    a := []int{7, 2, 8, -9, 4, 0}
        c := make(chan int)
    go sum(a[:len(a)/2], c)
    go sum(a[len(a)/2:], c)
        x, y := <-c, <-c  // receive from c
    (x, y, x + y)
}

I hope this article will be helpful to everyone's Go language programming.