Easy parallelization and concurrency:
package main
import (
"runtime"
)
func FoldParallel(data []float64, initialValue float64, op func(float64,
float64) float64) float64 {
sliceSize := len(data) / runtime.NumCPU()
results := make(chan float64, runtime.NumCPU())
numResults := 0
for i := 0; i < len(data); i += sliceSize {
numResults++
go func(dataSlice []float64) {
result := float64(initialValue)
for _, v := range dataSlice {
op(result, v)
}
results <- result
}(data[i : i+sliceSize])
}
result := initialValue
for i := 0; i < numResults; i++ {
result = op(result, <-results)
}
return result
}
func main() {
var data [1000]float64
// parallel sum
FoldParallel(data[:], 0, func(v1, v2 float64) float64 { return v1 + v2
})
// parallel mul
FoldParallel(data[:], 1, func(v1, v2 float64) float64 { return v1 * v2
})
}
--
You received this message because you are subscribed to the Google Groups
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
For more options, visit https://groups.google.com/d/optout.