Goroutines in Golang

Goroutines are one of the most important aspects of the Go programming language. It is the smallest unit of execution. This post explores the different aspects of a goroutine and how to work with it.

What is a goroutine?

A goroutine is a lightweight thread in Golang. It can continue its work alongside the main goroutine and thus creating concurrent execution.

Goroutine syntax

Creating a goroutine is really simple. We simply need to add keyword “go” in front of the function we want to run concurrently and it will work. Here is an example.

go FunctionName()

Goroutine example

Now, we will see a simple example of the working of a goroutine.

package main

import (
	"fmt"
	"time"
)

func f() {
	var i int
	for i = 0; i < 5; i++ {
		fmt.Print(i, " ")
	}
}

func main() {
	go f()
	f()
}
Go Goroutine Not Working
Go Goroutine Not Working

Now, this program will run. But, it will only print the first function and the goroutine will not be executed. This is a problem. The reason it happens is the main goroutine does not wait for the other goroutine to finish. It simply comes back to the main thread and executes without waiting for the goroutine to finish.

To fix that we can make the main goroutine sleep for a bit. That way we provide enough time for the goroutine to execute and finish. Here’s how we can do that.

package main

import (
	"fmt"
	"time"
)

func f() {
	var i int
	for i = 0; i < 5; i++ {
		time.Sleep(10 * time.Millisecond)
		fmt.Print(i, " ")
	}
}

func main() {
	go f()
	f()
}
Go Goroutine Example
Go Goroutine Example

This way the goroutine produces the required output.

Anonymous goroutines

Go has support for anonymous functions. Goroutines can be anonymous as well. Here is an example of an anonymous goroutine.

package main

import (
	"fmt"
	"time"
)

func PrintName(f string, l string) {
	fmt.Println(f, l)
}

func main() {
	var i int
	go func() {
		for i = 0; i < 7; i++ {
			fmt.Print(i, " ")
			time.Sleep(100 * time.Millisecond)
		}
	}()
	time.Sleep(1 * time.Second)
	PrintName("John", "Doe")
}

In this example, the anonymous function is created and executed immediately.

Go Anonymous Goroutine Example
Go Anonymous Goroutine Example

This program outputs as expected. Here we also use the sleep method otherwise it won’t work as expected.

When to use Goroutines in Golang

  • When one task can be split into different segments to perform better.
  • When making multiple requests to different API endpoints.
  • Any work that can utilize multi-core CPU should be well optimized using goroutines.
  • Running background operations in a program might be a use case for a goroutine.

Real-Life Use Cases of Goroutines or Concurrency

  • Reading a huge log file and process for exception or error messages
  • Posting multiple API calls in different threads when they are not dependent on each other
  • To implement “fire and forget” situation
  • Processing a huge SQL file to dump the data into tables.

Recommended: Mutex in Golang