Skip to content

Instantly share code, notes, and snippets.

@hackintoshrao
Last active April 5, 2022 07:37
Show Gist options
  • Save hackintoshrao/5a88f0fab29bd2d2a4062989a9520d91 to your computer and use it in GitHub Desktop.
Save hackintoshrao/5a88f0fab29bd2d2a4062989a9520d91 to your computer and use it in GitHub Desktop.
Simple program for concurrently summing up numbers.
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