Go routines are a way to execute functions in the background while the main program execution continues. This makes it possible to execute code asynchronously, resulting in great utility for running tasks in parallel.
If you are new to the world of Go, I recommend the following previous articles:
- Go basics
- Go functions
- Go unit tests
- Go pointers
- Go interfaces
- Go struct embedding
- Go generics
- Go errors
In the following sample code we are going to call a function in the traditional way first, and then call the same function using a goroutine. We’ll observe how going
appears after the goroutine, as the main thread of execution continues forward without being blocked while the goroutine executes.
vi goroutine.go
package main
import (
"fmt"
"time"
)
func f(from string) {
for i := 0; i < 4; i++ {
fmt.Println(from, ":", i)
}
}
func main() {
// Regular function call:
f("direct")
// GoRoutine function call:
go f("goroutine")
fmt.Println("going")
// Sleep 1s
time.Sleep(time.Second)
fmt.Println("done")
}
If we execute the code we will see the following output:
go run goroutine.go
direct : 0
direct : 1
direct : 2
direct : 3
going
goroutine : 0
goroutine : 1
goroutine : 2
goroutine : 3
done