主函数(main)只是一个普通的 goroutine 吗?

huangapple go评论84阅读模式
英文:

Is main just a normal goroutine?

问题

我目前正在阅读《Go并发模式》一书中的章节。我对第16页的一句话感到有些困惑,它与第19页上的另一句话似乎存在矛盾。在第16页上说:

当main函数返回时,程序退出,并将boring函数一同关闭。

而在第19页上(结合第20页上的示例)说:

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

如果main只是一个goroutine,它如何能够导致其他(派生的)goroutine停止呢?换句话说,main goroutine有何特殊之处?

我搜索了一下,但没有找到明显有启发性的答案;一个标题有希望的SO问题Go程序中main goroutine和派生的goroutine之间的区别问的是一个完全不同的问题。

编辑: 更改了标题,重点关注main和“普通”goroutine之间的区别(在遇到Go运行时函数Goexit时)。

编辑: 简化问题,更加专注于main的特殊性。

英文:

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?<sup>*</sup>


<sup>*</sup> 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

答案1

得分: 4

我认为你需要将goroutine的影响与进程的影响分开考虑。

main()函数是一个goroutine(或者如果你想要更准确的说法,是从一个隐式创建的goroutine中调用的)。使用go关键字可以创建其他的goroutine。从main()函数返回会终止它所在的goroutine,同时也会终止整个进程(因此也会终止所有其他的goroutine)。还可以通过在任何goroutine中调用os.Exit()或类似的方法来终止整个进程。

英文:

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.

huangapple
  • 本文由 发表于 2016年12月15日 19:45:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/41163398.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定