Last active
April 5, 2022 07:37
-
-
Save hackintoshrao/5a88f0fab29bd2d2a4062989a9520d91 to your computer and use it in GitHub Desktop.
Simple program for concurrently summing up numbers.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "fmt" | |
// function to add an array of numbers. | |
func sum(s []int, c chan int) { | |
sum := 0 | |
for _, v := range s { | |
sum += v | |
} | |
// writes the sum to the go routines. | |
c <- sum // send sum to c | |
} | |
func main() { | |
s := []int{7, 2, 8, -9, 4, 0} | |
c1 := make(chan int) | |
c2 := make(chan int) | |
// spin up a goroutine. | |
go sum(s[:len(s)/2], c1) | |
// spin up a goroutine. | |
go sum(s[len(s)/2:], c2) | |
x, y := <-c1, <-c2 // receive from c1 aND C2 | |
fmt.Println(x, y, x+y) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment