关于 Goroutine 数的疑问
直接上代码
// main.go
package main
import (
"fmt"
"runtime"
)
func main() {
num := runtime.NumGoroutine()
fmt.Println(num)
}
Go 中 main 函数其实也是跑在协程之下的一个函数.
所以下面这段代码会输出1个协程数, 表示理解.
go run main.go
1
但是在测试环境下
// num_test.go
package main
import (
"runtime"
"testing"
)
func TestNum(t *testing.T) {
t.Log(runtime.NumGoroutine())
}
go test -v num_test.go
=== RUN TestNum
--- PASS: TestNum (0.00s)
num_test.go:10: 2
PASS
为什么会默认有2个协程数?
测试的入口函数算1个, 那还有1个哪冒出来的?
推荐文章: