main只是一个普通的goroutine吗?

main只是一个普通的goroutine吗?

问题描述:

I'm currently reading the slices of Go Concurrency Patterns. I'm a little bit confused about a seeming contradiction between a statement on slide #16:

When main returns, the program exits and takes the boring function down with it.

and another one on slide #19 (in combination with the example on slide #20):

A channel in Go provides a connection between two goroutines, allowing them to communicate.

If main is just a goroutine, how can it cause any another (spawned) goroutine to stop, in other words: in what sense is the goroutine named main special?*


* I searched for it, but found nothing obviously enlightening so far; the SO question with the promising title Difference between the main goroutine and spawned goroutines of a Go program asks for a completely different issue.

edit: changed the title, to focus on the difference between main and "normal" goroutines (after stumbling upon the Go runtime function Goexit)

edit: simplified question, to be even more focused on the specifics of main

我目前正在阅读 Go并发模式 em>的内容。 关于幻灯片#16 a href =“ https://talks.golang.org/2012/concurrency.slide#16”上的声明之间似乎存在矛盾,我有些困惑。 a>: p>

当主程序返回时,程序退出并取消无聊功能。 p> blockquote> 和另一个幻灯片#a (与幻灯片#20上的示例): p>

Go中的通道提供了两个goroutine之间的连接,从而使它们能够进行通信。 p> blockquote>

如果 main code> 是 em>只是一个goroutine,它如何导致其他(生成的)goroutine停止,换句话说:在什么意义上,名为 main code>的goroutine有什么特殊之处? * sup > p>


* sup>我进行了搜索,但没有发现明显的问题 到目前为止 标题为 Go程序的主要goroutine与衍生的goroutine之间的区别 em> 要求一个完全不同的问题。 p>

编辑: strong> 标题,着重于主要和“普通” goroutines之间的区别(在绊倒Go运行时函数 Goexit ) p>

编辑: strong>简化了问题,将重点放在主要 p> div>的细节上

I think you need to consider the goroutine implications separately to the process implications.

The main() function is a goroutine (or if you want to be really picky, called from an implicitly created goroutine). Using go creates other goroutines. Returning from main() terminates its goroutine but also terminates the process as a whole (and thus all other goroutines). It is also possible to terminate the process as a whole by calling os.Exit() or similar from any goroutine.