Is the main()
function a goroutine? For example, I've seen a crash stack trace like the below, which makes me ask:
goroutine 1 [running]: main.binarySearch(0x0, 0x61, 0x43,
0xc420043e70, 0x19, 0x19, 0x10)
/home/---/go/src/github.com/----/sumnum.go:22 +0x80 main.main()
/home/---/go/src/github.com/---/sumnum.go:13 +0xc1 exit status 2
Yes, the main function runs in a goroutine (the main one).
According to https://tour.golang.org/concurrency/1
A goroutine is a lightweight thread managed by the Go runtime.
go f(x, y, z)
starts a new goroutine runningf(x, y, z)
The evaluation of f, x, y, and z happens in the current goroutine and the execution off
happens in the new goroutine.
Goroutines run in the same address space, so access to shared memory must be synchronized. The sync package provides useful primitives, although you won't need them much in Go as there are other primitives.
So according to this official document the main
runs in the current goroutine.
Now let's have some fun with main
and run this (So here the current goroutine runs the new goroutine) so here we have more than one goroutine which execute main()
again! (Note: Access to shared memory must be synchronized):
package main
import (
"fmt"
"time"
)
var i = 3
func main() {
if i <= 0 {
return
}
i--
fmt.Println("Hi")
go main()
time.Sleep(100 * time.Millisecond)
}
output:
Hi
Hi
Hi
Let's calculate factorial using main()
(one goroutine - no synchronization needed):
package main
import "fmt"
func main() {
if f <= 0 {
fmt.Println(acc)
return
}
acc *= f
f--
main()
}
var f = 5
var acc = 1
output:
120
Note: The codes above are just for clearly showing my viewpoints and is not good for production use (Using global variables should not be the first choice).
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 of confusion and problems.