goroutine example


If we call them with the go keyword they become go-routines and they start to work in parallel. So in this example you can see the output is mixed up.

examples/goroutine/goroutine.go
package main

import (
    "fmt"
    "time"
)

func count(n int, name string) {
    for i := 0; i < n; i++ {
        fmt.Printf("%s %d\n", name, i)
        time.Sleep(1000)
    }
}

func main() {
    fmt.Println("Welcome")
    count(3, "first")
    go count(3, "second")
    go count(3, "third")
    count(3, "fourth")
    fmt.Println("Done")
}

Welcome
first 0
first 1
first 2
fourth 0
second 0
second 1
third 0
third 1
second 2
fourth 1
third 2
fourth 2
Done