如何得到goroutine 的 id?

42 篇文章 1 订阅

Go中,系统是不提供goroutineid给外界的,丫的认为这事情不应该提供给用户来使用。

可有时候,实在是觉得这个东西必须得有呀,比方说后台开了个goroutine进行http请求的处理,这个免不了要打个日志什么的, 当并发量稍微大点的时候,就会发现这些信息的输出就交叉错乱在一起了。怎么区分。

一种方案是在http请求的时候,生成一个context的东西,里面有个值来表示是这个goroutine,然后打日志的时候将这个值输出来。 这种方案的问题是:你得将这个context显示的一路传递下去,显然这个这很多时候会很痛苦。

另一种方案是如果系统能够提供一个标识来表明这个goroutine的信息,那么就不必要这么麻烦了。所以考虑之后,决定采用这种获取系统的goroutine id的方案。

go1.6中具体方法是在src/runtime/proc.go尾部添加


// export Goid
func Goid() int64 {
    _g_ := getg()
    return _g_.goid
}

重新编译生成对应的go编译器(最好用go1.4来编译,省事),然后就可以在代码中用runtime.Goid获取到对应的id了。

线上跑了几个月,没有出现过异常,所以还是比较稳定的。

=============================================================================

使用Java的时候很容易得到线程的名字, 比如"Thread.currentThread().getName",这样就可以进行一些监控操作或者设置线程相关的一些数据。当转向Golang开发的时候,却发现Go语言并没有提供获取当前goroutine id的操作。这是Golang的开发者故意为之,避免开发者滥用goroutine id实现goroutine local storage (类似java的"thread-local" storage), 因为goroutine local storage很难进行垃圾回收。因此尽管以前暴露出了相应的方法,现在已经把它隐藏了。

Please don't use goroutine local storage. It's highly discouraged. In fact, IIRC, we used to expose Goid, but it is hidden since we don't want people to do this.

Potential problems include:

  1. when goroutine goes away, its goroutine local storage won't be GCed. (you can get goid for the current goroutine, but you can't get a list of all running goroutines)
  2. what if handler spawns goroutine itself? the new goroutine suddenly loses access to your goroutine local storage. You can guarantee that your own code won't spawn other goroutines,
    but in general you can't make sure the standard library or any 3rd party code won't do that.

thread local storage is invented to help reuse bad/legacy code that assumes global state, Go doesn't have legacy code like that, and you really should design your code so that state is passed explicitly and not as global (e.g. resort to goroutine local storage)

当然Go的这种隐藏的做法还是有争议的,有点因噎废食。在debug log的时候goroutine id是很好的一个监控信息。本文介绍了两种获取goroutine id的方法。

可以用纯Go语言获取当前的goroutine id。代码如下所示:

package main
import (
	"fmt"
	"runtime"
	"strconv"
	"strings"
	"sync"
)
func GoID() int {
	var buf [64]byte
	n := runtime.Stack(buf[:], false)
	idField := strings.Fields(strings.TrimPrefix(string(buf[:n]), "goroutine "))[0]
	id, err := strconv.Atoi(idField)
	if err != nil {
		panic(fmt.Sprintf("cannot get goroutine id: %v", err))
	}
	return id
}
func main() {
	fmt.Println("main", GoID())
	var wg sync.WaitGroup
	for i := 0; i < 10; i++ {
		i := i
		wg.Add(1)
		go func() {
			defer wg.Done()
			fmt.Println(i, GoID())
		}()
	}
	wg.Wait()
}
go run main.go 输出:

main 1
9 14
0 5
1 6
2 7
5 10
6 11
3 8
7 12
4 9
8 13



它利用runtime.Stack的堆栈信息。runtime.Stack(buf []byte, all bool) int会将当前的堆栈信息写入到一个slice中,堆栈的第一行为goroutine #### […,其中####就是当前的gororutine id,通过这个花招就实现GoID方法了。

但是需要注意的是,获取堆栈信息会影响性能,所以建议你在debug的时候才用它

参考资料

  1. https://groups.google.com/forum/#!topic/golang-nuts/Nt0hVV_nqHE
  2. http://wendal.net/2013/0205.html
  3. http://blog.sgmansfield.com/2015/12/goroutine-ids/
  4. http://dave.cheney.net/2013/09/07/how-to-include-c-code-in-your-go-package
  5. http://golanghome.com/post/566
  6. https://github.com/t-yuki/goid
  7. https://github.com/petermattis/goid.git
  8. https://github.com/huandu/goroutine


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值