特定goroutine运行的数量

huangapple go评论76阅读模式
英文:

Number of specific go routines running

问题

在Go的运行时库中,我们有NumGoroutine()函数来返回当前运行的goroutine总数。我想知道是否有一种简单的方法来获取特定函数运行的goroutine数量?

目前,我可以得到所有goroutine的数量,比如1000个,但我想知道运行func Foo函数的goroutine数量。有可能吗?简单吗?是否值得关注?

英文:

In go's runtime lib we have NumGoroutine() to return the total number of go routines running at that time. I was wondering if there was a simple way of getting the number of go routines running of a specific function?

Currently I have it telling me I have 1000, or whatever, of all go routines but I would like to know I have 500 go routines running func Foo. Possible? Simple? Shouldn't bother with it?

答案1

得分: 8

我很抱歉,如果你对这些数字感兴趣,你需要自己计算goroutines的数量。实现你的目标最简单的方法是直接使用sync/atomic包。

import "sync/atomic"

var counter int64

func example() {
    atomic.AddInt64(&counter, 1)
    defer atomic.AddInt64(&counter, -1)

    // ...
}

当你想要读取计数器的当前值时,请使用atomic.LoadInt64(&counter)

在程序中拥有几个这样的计数器并不罕见,这样你可以轻松地监控它。例如,可以查看最近发布的groupcache源代码中的CacheStats结构体。

英文:

I'm afraid you have to count the goroutines on your own if you are interested in those numbers. The cheapest way to achieve your goal would be to use the sync/atomic package directly.

import "sync/atomic"

var counter int64

func example() {
    atomic.AddInt64(&counter, 1)
    defer atomic.AddInt64(&counter, -1)

    // ...
}

Use atomic.LoadInt64(&counter) whenever you want to read the current value of the counter.

And it's not uncommon to have a couple of such counters in your program, so that you can monitor it easily. For example, take a look at the CacheStats struct of the recently published groupcache source.

huangapple
  • 本文由 发表于 2013年8月9日 02:33:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/18133502.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定