golang / go

The Go programming language
https://go.dev
BSD 3-Clause "New" or "Revised" License
124.1k stars 17.68k forks source link

runtime: A new method to get function created goroutine required. #11440

Closed ghost closed 9 years ago

ghost commented 9 years ago
$ go version
go version go1.4.2 linux/amd64

runtime.Stack() prints 'createdby', but there's no other way to access it. runtime.Caller() and runtime.Callers() does not provide goroutine creator info.

ianlancetaylor commented 9 years ago

What would this function return? What would the arguments be?

ghost commented 9 years ago

Ah sorry.

Return *runtime.Func and get one uimtptr as argument, like runtime.FuncForPc() But I don't what naming would be right for this

I wrote this on golang-nuts but it does not appears now

ianlancetaylor commented 9 years ago

I'm sorry, I still don't understand. What would the uintptr argument be?

Are you suggesting something like

func CreatedBy() *Func

which would return the function that created the current goroutine? Or something like

func CreatedBy() (pc uintptr, file string, line int, ok bool)

along the lines of Caller?

One thing I'm wondering about is how useful it is to get the creator of the current goroutine. I don't see any way to ask for the creator of any other goroutine.

Can you describe a use for this in practice?

ghost commented 9 years ago

I mean something like https://golang.org/pkg/runtime/#FuncForPC

func ParentFuncForPC(pc uintptr) *Func
or
func CreatorFuncForPC(pc uintptr) *Func

pc is program count of goroutine.

And this would allow priting even other function's goroutines, and test of net/http library use runtime.Stack() to do this. But it parse stack trace string. https://github.com/golang/go/blob/master/src/net/http/main_test.go#L26-L51

ianlancetaylor commented 9 years ago

It doesn't make sense to speak of printing other function's goroutines. A single function can be being run by many goroutines simultaneously. In your suggested functions, the pc argument seems unnecessary.

ghost commented 9 years ago

Hmm.. I didn't meaned

func Other() {
    // from here
    GetGoroutineOf(Parent) // instead of pc..
}

func Parent() { 
    go func() { // <- get this function
        // etc..
    }()
}

I meaned a function to get

func Parent() { // <- this function
    go func() {
        // etc..
    }()
}
ianlancetaylor commented 9 years ago

Please write a complete small example.

ghost commented 9 years ago

Maybe https://github.com/ceram1/gostack/blob/master/stack_test.go#L63-L80 this can be complete example.