147
edits
Changes
→Parallel
func MultiPI(samples int) float64 {
runtime.GOMAXPROCS(runtime.NumCPU())
cpus := runtime.NumCPU()
threadSamples := samples / cpus
results := make(chan float64, cpus)
for j := 0; j < cpus; j++ {
go func() {// spawn goroutine
var inside int
r := rand.New(rand.NewSource(time.Now().UnixNano()))
for i := 0; i < threadSamples; i++ {
x, y := r.Float64(), r.Float64()
}
}
results <- float64(inside) / float64(threadSamples) * 4
}()
}
var total float64
for i := 0; i < cpus; i++ {
total += <-results
}
return total / float64(cpus)
}
</syntaxhighlight>