Last active
March 20, 2021 03:53
-
-
Save natescode/603c1fd93b19747e7d264268a5371448 to your computer and use it in GitHub Desktop.
Golang Channels
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" | |
func sum(s []int, c chan int) { | |
sum := 0 | |
for _, v := range s { | |
sum += v | |
} | |
c <- sum // send sum to c | |
} | |
func main() { | |
numbers := []int{1,7, 2, 8, -9, 4, 0,11,-17,4,1,1,-23,15,2,-32,4,8,15,28,3} // an odd number of integers to sum | |
var( | |
threads,start,end int | |
) | |
var isOdd bool | |
if len(numbers)%2 == 1{ | |
isOdd = true | |
} | |
threads = len(numbers)/5 | |
c := make(chan int) | |
for i := 0; i < threads; i++ { | |
start = i * 5 | |
end = start + 5 | |
if i+1 == threads && isOdd { | |
end++ | |
} | |
go sum(numbers[i*5:end],c) | |
} | |
var sum int | |
for i := 0; i < threads; i++{ | |
val := <-c | |
sum = sum + int(val) | |
} | |
fmt.Println(sum) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment