A goroutine is a function that can run concurrently. You can see it as a lightweight thread.
The idea stems from concurrency: working on more than one task simultaniously.

To invoke a Go routine, write go before the function call.

If you have a function f(string), call it as go f(string) to invoke it as goroutine. The function will then run asynchronously.

Download PDF

Example

Introduction

The code below invokes a goroutine, calls the function and waits for keyboard input. The goroutine is executed concurrently.

1
2
3
go f("go routine")
f("function")
fmt.Scanln()

Go doesn’t wait for goroutines to finished, it will return to the next line and run a goroutine concurrently. Without fmt.Scanln() Go would finish the program.

Goroutine

The goroutine defined f(msg string) is a simple function that outputs a line of text. It is called both as a regular function and as a goroutine.

Goroutines are light on memory, a program can easily have hundreds or thousands of goroutines.

This example starts a goroutine:

1
2
3
4
5
6
7
8
9
10
11
12
13
package main

import "fmt"

func f(msg string) {
fmt.Println(msg)
}

func main() {
go f("go routine")
f("function")
fmt.Scanln()
}
$ go run example.go
function
go routine

Exercises

  • What is a goroutine?
  • How can you turn a function into a goroutine?
  • What is concurrency?