SoFunction
Updated on 2025-03-04

Method for implementing multi-core parallel operation in go language channel

This article describes the method of implementing multi-core parallel operation in Go language channel. Share it for your reference. The details are as follows:

Here is an Add function that returns the sum of two integers and uses a go statement to perform parallel operations. In order to wait for each parallel operation to obtain its return value, a channel needs to be introduced.

Copy the codeThe code is as follows:
package main
import "fmt"
func Add(x int,y int,channel chan int) {
    sum := (x,y)
    (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 will be helpful to everyone's Go language programming.