每纤程groutine 大约8K 内存
// Concurrent computation of pi.
// See https://goo.gl/la6Kli.
//
// This demonstrates Go's ability to handle
// large numbers of concurrent processes.
// It is an unreasonable way to calculate pi.
package main
import (
"bufio"
"fmt"
"math"
"os"
"sync"
)
var w sync.WaitGroup
func main() {
fmt.Println(pi(10000))
}
// pi launches n goroutines to compute an
// approximation of pi.
func pi(n int) float64 {
ch := make(chan float64)
ch2 := make(chan float64)
for k := 0; k <= n; k++ {
w.Add(1)
go term(ch, ch2, float64(k))
}
f := 0.0
for k := 0; k <= n; k++ {
f += <-ch
}
reader := bufio.NewReader(os.Stdin)
reader.ReadLine()
for k := 0; k <= n; k++ {
ch2 <- 1.0
}
w.Wait()
return f
}
func term(ch, ch2 chan float64, k float64) {
ch <- 4 * math.Pow(-1, k) / (2*k + 1)
<-ch2
w.Done()
}
1万线程 内存 87M,
10万线程 内存861M 0.635301秒创建线程 ,创建线程花费很低。
有疑问加站长微信联系(非本文作者)