How to define a goroutine?

Let's say I have a stacktrace for a bunch of goroutines, e. g :.

goroutine 5633 [select]:
net/http.(*persistConn).writeLoop(0xc21303ac00)
    /usr/lib/go/src/pkg/net/http/transport.go:791 +0x271
created by net/http.(*Transport).dialConn
    /usr/lib/go/src/pkg/net/http/transport.go:529 +0x61e

      

In my case, a set of application-specific objects are served by a set of goroutines, and I want to look at the stack of gotoutines related to a specific object. I have hundreds of application specific objects, so I end up with hundreds of identical goroutines.

How can I link my logs to goroutines on the stack? There seems to be no way to identify the current goroutine in the stack trace and not call the goroutine in any way, so I can see the specific value in the stack trace.

PS

I've already read related "why-would-you-want-to-do" posts on the Go mailing list, so I'm looking for alternatives / hacks / workarounds (which hopefully don't require code to call every other line in the log) ...

+3


source to share


1 answer


A workaround is possible and includes a small piece of C code.

goid.c

#include <runtime.h>
void ·GetGoID(int32 ret) {
    ret = g->goid;
    USED(&ret);
}

      

main.go



package main
import (
    "fmt"
    "sync"
)
// Declaration is required
func GetGoID() int32
func main() {
    var wg sync.WaitGroup
    f := func() {
        wg.Add(1)
        go func() {
            fmt.Printf("goroutine %d\n", GetGoID())
            wg.Done()
        }()
    }
    for i := 0; i < 10; i++ {
        f()
    }
    wg.Wait()
}

      

Build and run

$ go build
$ ./example
goroutine 20
goroutine 21
goroutine 22
goroutine 23
goroutine 24
goroutine 25
goroutine 26
goroutine 27
goroutine 28
goroutine 29

      

+3


source







All Articles