3
votes

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

1
What do you mean by "how can it take control over another goroutine," ? There's does not appear to be any mentioning of a goroutine taking control over something else . Note that when the program returns from main(), the entire process dies/exits. main() is almost "just" a gouroutine. But it's special since naturally this is where execution of the entire program starts (besides any init() functions being run), and when main() ends, the process dies. - nos
The runtime will make a goroutine and call main with it. When main returns, the runtime will exit. It's like with most programming languages: returning from main exits the program, irrespective of any threads you might have spawned. - Alexander Torstling
Who said main is a goroutine? - RickyA
@RickyA, I am a newbie and you are confusing me now! The book I am reading (Programming in Go - Mark Summerfield) says this "A goroutine is a function or method invocation that executes independently and concurrently in relation to any other goroutines in a program. Every Go program has at least one goroutine, the main goroutine in which the main package’s main() function executes. ...". - Cetin Basoz
@Wolf: See golang-book.com/books/intro/10 , "The first goroutine is implicit and is the main function itself". - Alexander Torstling

1 Answers

4
votes

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.