From dae1d39dd70e5c98a737cadc4f218b79867dc663 Mon Sep 17 00:00:00 2001 From: Stefan Lankes Date: Sat, 10 Sep 2016 17:31:18 +0200 Subject: [PATCH] add example, which creates a goroutine per core --- hermit/usr/gcc | 2 +- hermit/usr/tests/pi.go | 30 +++++++++++++++++++++++------- 2 files changed, 24 insertions(+), 8 deletions(-) diff --git a/hermit/usr/gcc b/hermit/usr/gcc index d686639af..07585ecfd 160000 --- a/hermit/usr/gcc +++ b/hermit/usr/gcc @@ -1 +1 @@ -Subproject commit d686639afb35650edf0d55647b7e8b30e8f1f989 +Subproject commit 07585ecfdbc69ec9cceadf4dcd0fdf1eb855d3e1 diff --git a/hermit/usr/tests/pi.go b/hermit/usr/tests/pi.go index a6d41e234..e1fddebc5 100644 --- a/hermit/usr/tests/pi.go +++ b/hermit/usr/tests/pi.go @@ -32,17 +32,26 @@ import ( "os" "strconv" "time" + "runtime" ) -func term(i int, step float64) (x float64) { - x = (float64(i) + 0.5) * step - x = 4.0 / (1.0 + x * x) +var step float64 - return +func term(ch chan float64, start, end int) { + var res float64 + + for i := start; i < end; i++ { + x := (float64(i) + 0.5) * step + res += 4.0 / (1.0 + x * x) + } + + ch <- res } func main() { var num_steps int + ch := make(chan float64) + max_coroutines := runtime.NumCPU() if len(os.Args) > 1 { num_steps, _ = strconv.Atoi(os.Args[1]) @@ -53,12 +62,19 @@ func main() { fmt.Println("num_steps = ", num_steps) sum := float64(0) - step := 1.0 / float64(num_steps) + step = 1.0 / float64(num_steps) start := time.Now() - for i := 0; i < num_steps; i++ { - sum += term(i, step) + for i := 0; i < max_coroutines; i++ { + start := (num_steps / max_coroutines) * i + end := (num_steps / max_coroutines) * (i+1) + + go term(ch, start, end) + } + + for i := 0; i < max_coroutines; i++ { + sum += <-ch } elapsed := time.Since(start)