Golang的纤程耗费
森_98ad · · 1265 次点击 · · 开始浏览每纤程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秒创建线程 ,创建线程花费很低。
有疑问加站长微信联系(非本文作者)
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
关注微信- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码` - 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传
收入到我管理的专栏 新建专栏
每纤程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秒创建线程 ,创建线程花费很低。