개발자 이야기/Go
go routine ID 획득하기.
sonumb
2021. 10. 27. 13:42
직접 호출 할 수 있는 함수는 제공되지 않는 듯 하다.
아래 코드를 이용하여 id를 획득하는 것으로 해결함.
간단히 설명하자면 콜스택에 ID가 기입되어 있는데, 이를 획득하여 타입변환후 반환하는 코드다.
https://gist.github.com/metafeather/3615b23097836bc36579100dac376906
Get goroutine id for debugging
Get goroutine id for debugging. GitHub Gist: instantly share code, notes, and snippets.
gist.github.com
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():", goid())
}()
}
wg.Wait()
}
반응형