Last active
August 29, 2015 14:21
-
-
Save PotcFdk/b1e8ea1583728177134a to your computer and use it in GitHub Desktop.
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
/* pi-goroutines.go | |
* This spams Goroutines to calculate pi. | |
* Not a great approach, I just wanted to play around with Goroutines and channels. | |
* | |
* PotcFdk, 2015 | |
*/ | |
package main | |
import ( | |
"fmt" | |
"math" | |
"runtime" | |
"sync" | |
) | |
func main() { | |
fmt.Println(calcpi(1e8)) | |
} | |
const cap int = 1e6 | |
var free int = cap | |
var wg sync.WaitGroup | |
func calcpi(n int) float64 { | |
ch := make(chan float64) | |
remaining := n | |
go collector( ch, n) | |
wg.Add(1) | |
for remaining > 0 { | |
for free > 0 && remaining > 0 { | |
go term (ch, float64(n - remaining)) | |
free-- | |
remaining-- | |
} | |
runtime.Gosched() | |
} | |
wg.Wait() | |
return <-ch | |
} | |
func collector (ch chan float64, total int) { | |
sum := float64 (0.0) | |
fmt.Println ("Started collector, waiting for: ", total) | |
for k := 0; k < total; k++ { | |
sum += <-ch | |
free++ | |
if k % 1e6 == 0 { | |
fmt.Printf ("progress: %d/%d (%d %%)\n", k, total, int(float64(k)/float64(total) * 100)) | |
} | |
} | |
fmt.Println ("Collector finished.") | |
wg.Done() | |
ch <- sum | |
} | |
func term (ch chan float64, k float64) { | |
ch <- 4 * math.Pow(-1, k) / (2*k + 1) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Terminal output: