Basic Go Routines (like Threading)

· 194 words · 1 minute read

This script basically just prints out the numbers 1 to 10, but it does so by spinning off each print statement into it’s own thread, using a go routine. You’ll notice the script also has a start and an end print statement, but because go routines are used, the end statement will be printed before and items (1-10) are printed.

The ending sleep allows the go routines to execute as they were being cut short by the main function finished, thus ending the programs life.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package main

import (
    "fmt"
    "time"
)

func main() {
    fmt.Println("Start Script")

    for i := 0; i < 10; i++ {
        go printItem(i)
    }

    fmt.Println("End Script")

    // Wait, giving time for the go routines
    // to finish.
    time.Sleep(1000)
}

func printItem(i int) {
    fmt.Printf("Print Item: %v\n", (i + 1))
}

Output:

Start Script
End Script
Print Item: 1
Print Item: 2
Print Item: 3
Print Item: 4
Print Item: 5
Print Item: 6
Print Item: 7
Print Item: 8
Print Item: 9
Print Item: 10

Image of Author Edd Turtle

Author:  Edd Turtle

Edd is the Lead Developer at Hoowla, a prop-tech startup, where he spends much of his time working on production-ready Go and PHP code. He loves coding, but also enjoys cycling and camping in his spare time.

See something which isn't right? You can contribute to this page on GitHub or just let us know in the comments below - Thanks for reading!