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.

Example

Introduction

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


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:


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?