Goroutines

Duration: 15 min  •  Difficulty: Hard

Goroutines are Go's "killer app" feature. They allow functions to run in the background (asynchronously) concurrently with other functions.

Difference with Threads

Goroutines are much lighter than OS Threads. You can run thousands of Goroutines simultaneously with very little memory.

How to use

Simply add the go keyword in front of the function call.

MAIN.GO
package main
import (
"fmt"
"time"
)
func printNumber(label string) {
for i := 1; i <= 3; i++ {
time.Sleep(100 * time.Millisecond)
fmt.Println(label, ":", i)
}
}
func main() {
// Run in the background (New thread-like)
go printNumber("Background")
// Run in the main thread
printNumber("Main")
// We need to wait a bit, because if main finished,
// all background goroutines will be forced to shut down.
time.Sleep(500 * time.Millisecond)
}