回答

收藏

goroutine 的最大数量

技术问答 技术问答 567 人阅读 | 0 人回复 | 2023-09-11

我能用多少个 ?goroutine?比如维基百科说 Erlang 可在不降低性能的情况下,在不降低性能的情况下。/ E0 R3 i" R- y3 O8 G( p
更新:我刚刚调查了 goroutines 性能并得到这样的结果:3 l3 |7 N& |; ]" W- l; c
看起来 goroutine 生命周期比 sqrt() 计算 1000 次(对我来说大约是 45μs)更重要的是,唯一的限制是内存
4 j# J& E$ {( W6 e' KGoroutine花费 4 - 4.5 KB
                                                               
' Z# w, ^) D) t/ z$ \    解决方案:                                                               
8 s! Z0 Q2 F7 p! z( M( E, g                                                                如果一个 goroutine 被堵塞,除:
& ^8 ]& O% [$ i& S) a使用内存
8 p9 z/ a3 {2 w: A+ `. u, R垃圾收集较慢
成本goroutine 平均时间为:% Q7 m7 s  }9 ^9 }8 J
    Go 1.6.2 (April 2016)  32-bit x86 CPU (A10-7850K 4GHz)    | Number of goroutines: 100000    | Per goroutine:    |   Memory: 4536.84 bytes    |   Time:   1.634248 μs  64-bit x86 CPU (A10-7850K 4GHz)    | Number of goroutines: 100000    | Per goroutine:    |   Memory: 4707.92 bytes    |   Time:   1.842097 μsGo release.r60.3 (December 2011)  32-bit x86 CPU (1.6 GHz)    | Number of goroutines: 100000    | Per goroutine:    |   Memory: 4243.45 bytes    |   Time:   5.815950 μs
    8 B( x# p; Z; S6 Z* l- j/ x
4 GB 内存的机器上,这将 goroutine 的最大限额略低于 100万 。
& `& E/ `" o. s# P! ?  i源代码(如果您已经理解上面打印的数字,则无需阅读):
+ T( Z- D% z9 K
    package mainimport  &quot;flag&quot;    &quot;fmt&quot;    &quot;os&quot;    &quot;runtime&quot;    &quot;time&quot;)var n = flag.Int(&quot;n&quot;,1e5,&quot;Number of goroutines to create&quot;)var ch = make(chan byte)var counter = 0func f()      counter      <-ch // Block this goroutine}func main()      flag.Parse()    if *n <=             fmt.Fprintf(os.Stderr,&quot;invalid number of goroutines&quot;)            os.Exit(1)     Limit the number of spare OS threads to just 1    runtime.GOMAXPROCS(1)    / Make a copy of MemStats    var m0 runtime.MemStats    runtime.ReadMemStats(&m0)    t0 := time.Now().UnixNano()    for i := 0; i < *n; i                     go f()    }    runtime.Gosched()    t1 := time.Now().UnixNano()    runtime.GC()    // Make a copy of MemStats    var m1 runtime.MemStats    runtime.ReadMemStats(&m1)    if counter != *n                fmt.Fprintf(os.Stderr,&quot;failed to begin execution of all goroutines&quot;)            os.Exit(1)      fmt.Printf(&quot;Number of goroutines: %d\n&quot;,*n)    fmt.Printf(&quoter goroutine:\n&quot;)    fmt.Printf(&quot;  Memory: %.2f bytes\n&quot;,float64(m1.Sys-m0.Sys)/float64(*n))    fmt.Printf(&quot;  Time:   %f μs\n&quot;,float64(t1-t0)/float64(*n)/1e3)}; i3 N( t2 z! U6 f! Y
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则