Working with GoRoutines in Go

11.25.2021

Intro

Go routines allow you to execute operations or functions concurrently. These are Go's way of handling multi-threading or asynchronous programming. In this article, we will learn how to us Goroutines.

A Basic Go Routine

Let's say we have a function that computes a large calculation. We will do a simple sum for our example.

func sum(nameOfSum string) {
	fmt.Println("Starting ", nameOfSum)
	sum := 0
	for i := 0; i < 10; i++ {
		sum += i
	}
	fmt.Println("Result for: ", nameOfSum, " is ", sum)
}

We can call this function multiple times using the go keywords and our sums will be computed in parallel, speeding up our program.

func main() {
	go sum("first")
	go sum("second")
	go sum("third")

	// Sleep for a second to wait for the tasks to complete
	time.Sleep(time.Second)
}

When we run our program, we get a result like to following. Note, that you may receive a different output as there is no order guarantee.

We can see in the run below, the third call was completed first. Despite the output, note that go does not wait to complete a function before running another. All of these functions are run in parallel.

Starting  third
Result for:  third  is  45
Starting  first
Result for:  first  is  45
Starting  second
Result for:  second  is  45

One problem above is that we had to add a time out to wait one second. We can solve this problem with WatiGroups which will be covered in a separate article.

The Full Example

Here is the full example code. You can run this by copying the contents into a file called main.go and then running go run main.go.

package main

import (
	"fmt"
	"time"
)

func sum(nameOfSum string) {
	fmt.Println("Starting ", nameOfSum)
	sum := 0
	for i := 0; i < 10; i++ {
		sum += i
	}
	fmt.Println("Result for: ", nameOfSum, " is ", sum)
}

func main() {
	go sum("first")
	go sum("second")
	go sum("third")

	// Sleep for a second to wait for the tasks to complete
	time.Sleep(time.Second)
}