回答

收藏

goroutine 的最大数量

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

我能用多少个 ?goroutine?比如维基百科说 Erlang 可在不降低性能的情况下,在不降低性能的情况下。
1 q: Z( o" V. f: z) Q" a& @更新:我刚刚调查了 goroutines 性能并得到这样的结果:
# \7 w: q" `- `1 x4 r/ [  W& c看起来 goroutine 生命周期比 sqrt() 计算 1000 次(对我来说大约是 45μs)更重要的是,唯一的限制是内存
& a  s2 }0 u$ U* i  E5 o  wGoroutine花费 4 - 4.5 KB
                                                                # s7 a3 G" Y  C' G) R' C4 U* t
    解决方案:                                                                : U9 u) s* @8 Z' r
                                                                如果一个 goroutine 被堵塞,除:
2 v7 |/ u: u) f2 y5 t使用内存
3 \2 s3 m- Q: F5 a垃圾收集较慢
成本goroutine 平均时间为:8 s; A$ ]$ ]+ D5 k1 z0 f0 b
    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' i0 j8 Q, ]) x2 |. D) I; h
4 GB 内存的机器上,这将 goroutine 的最大限额略低于 100万 。: [) p% r0 k% x# O
源代码(如果您已经理解上面打印的数字,则无需阅读):. Y) r$ p, J* X& P
    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)}4 T$ F4 u8 b0 B" Z5 g3 r+ J
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则