Skip to content

Instantly share code, notes, and snippets.

@jamesgarfield
Created April 26, 2013 18:43
Show Gist options
  • Save jamesgarfield/5469468 to your computer and use it in GitHub Desktop.
Save jamesgarfield/5469468 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
)
const NCPU = 16
func main() {
sum := Concurrent(1000)
fmt.Printf("Sum: %i", sum)
}
func Serial(max int64) int64 {
sum := int64(0)
for i := int64(1); i < max; i++ {
if i%3 == 0 || i%5 == 0 {
sum += i
}
}
return sum
}
func Concurrent(max int64) int64 {
c := make(chan int64, NCPU)
//Send discrete ranges to each goroutine to get calculated independantly.
for i := int64(0); i < NCPU; i++ {
go CalculateSum(i*max/NCPU, (i+1)*max/NCPU, c)
}
var sum int64
sum = 0
for i := int64(0); i < NCPU; i++ {
sum += <-c
}
return sum
}
func CalculateSum(min, max int64, c chan int64) {
sum := int64(0)
for i := min; i < max; i++ {
if i%3 == 0 || i%5 == 0 {
sum += i
}
}
c <- sum
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment