Skip to content

Instantly share code, notes, and snippets.

@mix3
Last active August 29, 2015 14:13
Show Gist options
  • Save mix3/2adb2e8c1970cf40d102 to your computer and use it in GitHub Desktop.
Save mix3/2adb2e8c1970cf40d102 to your computer and use it in GitHub Desktop.
runtime.StackからgoroutineIDを取得する
package main
import (
"log"
"runtime"
"sync"
)
func goroutineId() string {
buf := make([]byte, 1024)
runtime.Stack(buf, false)
id := []byte{}
if string(buf[0:9]) == "goroutine" {
for _, c := range buf[10:] {
if string(c) == " " {
break
}
id = append(id, c)
}
}
return string(id)
}
func main() {
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
wg.Add(1)
go func() {
log.Println(goroutineId())
wg.Done()
}()
}
wg.Wait()
}
@mix3
Copy link
Author

mix3 commented Jan 11, 2015

$ go run runtime.stack.parse.go
2015/01/11 14:00:42 5
2015/01/11 14:00:42 6
2015/01/11 14:00:42 7
2015/01/11 14:00:42 8
2015/01/11 14:00:42 9
2015/01/11 14:00:42 10
2015/01/11 14:00:42 11
2015/01/11 14:00:42 12
2015/01/11 14:00:42 13
2015/01/11 14:00:42 14

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment