goroutine 的最大数量 [英] Max number of goroutines

查看:68
本文介绍了goroutine 的最大数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以无痛地使用多少个 goroutine?例如维基百科说,在 Erlang 中可以创建 2000 万个进程而不会降低性能.

How many goroutines can I use painless? For example wikipedia says, in Erlang 20 million processes can be created without degrading performance.

更新:我刚刚调查在 goroutines 中的表现 得到了这样的结果:

Update: I've just investigated in goroutines performance a little and got such a results:

  • 看起来 goroutine 的生命周期比 sqrt() 计算 1000 次(对我来说约为 45 微秒),唯一的限制是内存
  • Goroutine 花费 4 — 4.5 KB

推荐答案

如果一个 goroutine 被阻塞,除了:

If a goroutine is blocked, there is no cost involved other than:

  • 内存使用
  • 较慢的垃圾收集

成本(就内存和实际开始执行 goroutine 的平均时间而言)是:

The costs (in terms of memory and average time to actually start executing a goroutine) are:

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 µs

Go 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

在安装了 4 GB 内存的机器上,这将 goroutine 的最大数量限制在略低于 100 万个.

On a machine with 4 GB of memory installed, this limits the maximum number of goroutines to slightly less than 1 million.

源代码(如果您已经理解上面打印的数字,则无需阅读):

Source code (no need to read this if you already understand the numbers printed above):

package main

import (
    "flag"
    "fmt"
    "os"
    "runtime"
    "time"
)

var n = flag.Int("n", 1e5, "Number of goroutines to create")

var ch = make(chan byte)
var counter = 0

func f() {
    counter++
    <-ch // Block this goroutine
}

func main() {
    flag.Parse()
    if *n <= 0 {
            fmt.Fprintf(os.Stderr, "invalid number of goroutines")
            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, "failed to begin execution of all goroutines")
            os.Exit(1)
    }

    fmt.Printf("Number of goroutines: %d
", *n)
    fmt.Printf("Per goroutine:
")
    fmt.Printf("  Memory: %.2f bytes
", float64(m1.Sys-m0.Sys)/float64(*n))
    fmt.Printf("  Time:   %f µs
", float64(t1-t0)/float64(*n)/1e3)
}

这篇关于goroutine 的最大数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆