gpt4 book ai didi

go - 默认的 goroutine 是什么?

转载 作者:IT王子 更新时间:2023-10-29 02:03:37 29 4
gpt4 key购买 nike

以下代码打印 2009/11/10 23:00:00 Num of goroutines: 1。有没有办法知道它是哪个 go 例程?

package main

import (
"log"
"runtime"
)

func main() {
r := runtime.NumGoroutine()
log.Println("Num of goroutines: ", r)
}

https://play.golang.org/p/pFOG6EQEYb

最佳答案

是主goroutine,封装了执行的主线程。例如,您可能会通过在示例程序中打印 goroutine 堆栈跟踪来观察:

package main

import (
"log"
"os"
"runtime"
"runtime/pprof"
)

func main() {
r := runtime.NumGoroutine()
log.Println("Num of goroutines: ", r)
pprof.Lookup("goroutine").WriteTo(os.Stdout, 1)
}

产生以下内容:

2009/11/10 23:00:00 Num of goroutines:  1
goroutine profile: total 1
1 @ 0xa22a0 0xa1fc0 0x9d640 0x20180 0x5a0a0 0x98e81
# 0xa229f runtime/pprof.writeRuntimeProfile+0xdf /usr/local/go/src/runtime/pprof/pprof.go:614
# 0xa1fbf runtime/pprof.writeGoroutine+0x9f /usr/local/go/src/runtime/pprof/pprof.go:576
# 0x9d63f runtime/pprof.(*Profile).WriteTo+0xff /usr/local/go/src/runtime/pprof/pprof.go:298
# 0x2017f main.main+0x17f /tmp/sandbox832735226/main.go:13
# 0x5a09f runtime.main+0x39f /usr/local/go/src/runtime/proc.go:183

请注意跟踪底部的 runtime.main

转储痕迹时有两个 goroutine 的程序:

package main

import (
"log"
"os"
"runtime"
"runtime/pprof"
)

func main() {
c := make(chan int)
go func() { <-c }()
r := runtime.NumGoroutine()
log.Println("Num of goroutines: ", r)
pprof.Lookup("goroutine").WriteTo(os.Stdout, 1)
}

将产生以下内容:

2009/11/10 23:00:00 Num of goroutines:  2
goroutine profile: total 2
1 @ 0x20220 0x98f61
# 0x20220 main.main.func1+0x0 /tmp/sandbox584983760/main.go:12

1 @ 0xa2380 0xa20a0 0x9d720 0x201e0 0x5a180 0x98f61
# 0xa237f runtime/pprof.writeRuntimeProfile+0xdf /usr/local/go/src/runtime/pprof/pprof.go:614
# 0xa209f runtime/pprof.writeGoroutine+0x9f /usr/local/go/src/runtime/pprof/pprof.go:576
# 0x9d71f runtime/pprof.(*Profile).WriteTo+0xff /usr/local/go/src/runtime/pprof/pprof.go:298
# 0x201df main.main+0x1df /tmp/sandbox584983760/main.go:15
# 0x5a17f runtime.main+0x39f /usr/local/go/src/runtime/proc.go:183

关于go - 默认的 goroutine 是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41818599/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com