Is the main function runs as a goroutine?

前端 未结 3 1552
慢半拍i
慢半拍i 2020-12-12 00:03

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:49

    Is the main function a goroutine?

    No.

    The main function is a function.

    In contrast,

    A goroutine is a lightweight thread of execution. (source).

    So goroutines execute functions, but goroutines are not functions, and there is not a 1-to-1 relationship between goroutines and functions.

    However...

    The main() function is executed in the first (and at startup, only) goroutine, goroutine #1.

    But as soon as that function calls another function, then the main goroutine is no longer executing the main function, and is instead executing some other function.

    So it's clear that a goroutine and a function are entirely different entities.

    Do not conflate goroutines with functions!!

    Functions and goroutines are entirely different concepts. And thinking of them as the same thing will lead to countless confusion and problems.

提交回复
热议问题