Example of Channel pipe usage in the Go language

  • 2020-05-26 09:17:26
  • OfStack

This article illustrates the use of Channel for pipes in the Go language. Share with you for your reference. The specific analysis is as follows:

channel is a typed pipe that can be used with the channel operator < - send or receive values to it.
ch < -v // feed v into channel ch.
v := < -ch // received from ch and assigned to v.
(the "arrow" is the direction of the data flow.)
Like map and slice 1, channel must be created before use:
ch := make(chan int)
By default, both send and receive are blocked until the other end is ready. This allows goroutine to synchronize without an explicit lock or race variable.

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
    fmt.Println(x, y, x + y)
}

I hope this article has helped you with your Go programming.


Related articles: