Is the main function runs as a goroutine?

前端 未结 3 821
野的像风
野的像风 2020-12-12 00:28

Is the main() function runs as a goroutine? For example, I\'ve seen a crash stack trace like the below, which makes me ask:

goroutine 1 [running         


        
3条回答
  •  旧巷少年郎
    2020-12-12 00:52

    Yes. Main func can spawn other goroutines, but "main" itself is one groutine.

    package main
    
    import (
            "fmt"
            "runtime"
    )
    
    func main() {
            // Goroutine num includes main processing
            fmt.Println(runtime.NumGoroutine()) // 1
    
            // Spawn two goroutines
            go func() {}()
            go func() {}()
    
            // Total three goroutines run
            fmt.Println(runtime.NumGoroutine()) // 3
    }
    

提交回复
热议问题