go language channel implements the method of multi core parallelization

  • 2020-05-17 05:40:54
  • OfStack

The example of this article describes the implementation of go language channel multi-core parallelization. Share with you for your reference. The details are as follows:

Here, an Add function is defined to return the sum of two integers. The go statement is used for parallelization. In order to wait for the end of each parallel operation to get its return value, channel needs to be introduced

package main
import "fmt"
func Add(x int,y int,channel chan int) {
    sum := library.Add(x,y)
    fmt.Println(sum)
    channel <- 1
}
func main() {
    n:=10 
    channel := make(chan int ,n)
    for i:=0;i<n;i++{
        go Add(1,i,channel)
    }
    for i:=0;i<n;i++{
 
        <- channel
    }
}

Final output:

1
2
3
4
5
6
7
8
9
10

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


Related articles: