concurrent_pi.go 989 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. // Concurrent computation of pi.
  2. // See http://goo.gl/ZuTZM. - Comparison with Scala!
  3. //
  4. // This demonstrates Go's ability to handle
  5. // large numbers of concurrent processes.
  6. // It is an unreasonable way to calculate pi.
  7. package main
  8. import (
  9. "fmt"
  10. "math"
  11. "time"
  12. )
  13. func main() {
  14. start := time.Now()
  15. fmt.Println(CalculatePi(5000))
  16. end := time.Now()
  17. delta := end.Sub(start)
  18. fmt.Printf("longCalculation took this amount of time: %s\n", delta)
  19. }
  20. // CalculatePi launches n goroutines to compute an
  21. // series-approximation of pi.
  22. func CalculatePi(n int) float64 {
  23. ch := make(chan float64)
  24. for k := 0; k <= n; k++ {
  25. // calculate k-th term in the series
  26. go term(ch, float64(k))
  27. }
  28. f := 0.0
  29. //wait for all goroutines to complete, get and sum up their results:
  30. for k := 0; k <= n; k++ {
  31. f += <-ch
  32. }
  33. return f
  34. }
  35. func term(ch chan float64, k float64) {
  36. ch <- 4 * math.Pow(-1, k) / (2*k + 1)
  37. }
  38. /* Output:
  39. 3.14179261359579
  40. The calculation took this amount of time: 0.028002
  41. */