Created
May 22, 2015 19:06
-
-
Save RabeaWahab/b2a305c2f65bc383965c to your computer and use it in GitHub Desktop.
Calculation of PI using multicores, http://www.soroushjp.com/2015/02/07/go-concurrency-is-not-parallelism-real-world-lessons-with-monte-carlo-simulations/
This file contains 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" | |
"math/rand" | |
"time" | |
"runtime" | |
) | |
func init() { | |
runtime.GOMAXPROCS(runtime.NumCPU()) | |
rand.Seed(time.Now().UnixNano()) | |
} | |
func MultiPI(samples int) float64 { | |
cpus := runtime.NumCPU() | |
threadSamples := samples / cpus | |
results := make(chan float64, cpus) | |
fmt.Println(cpus); | |
for j := 0; j < cpus; j++ { | |
go func() { | |
var inside int | |
r := rand.New(rand.NewSource(time.Now().UnixNano())) | |
for i := 0; i < threadSamples; i++ { | |
x, y := r.Float64(), r.Float64() | |
if x*x+y*y <= 1 { | |
inside++ | |
} | |
} | |
results <- float64(inside) / float64(threadSamples) * 4 | |
}() | |
} | |
var total float64 | |
for i := 0; i < cpus; i++ { | |
total += <-results | |
} | |
return total / float64(cpus) | |
} | |
func main () { | |
fmt.Println(MultiPI(1000000000)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment