How to create Goroutine in Golang with Examples

In this tutorial, we will learn about how to create Goroutine in Golang with examples. It is a special feature of Golang which has been developed to mitigate the complexity of traditional thread which are used to achieve concurrency in programming world.

 

Overview

To understand the Goroutine in Golang, we first must understand what threads are in programming world. So let’s talk little bit about threads from programming perspective.
In programing world, thread is refer to the smallest unit of execution within a process. It allows a program to multi task concurrently.  If threads are created within the same process, they will share the same memory space and resources making it possible to do parallel computations. The main purpose of threads are to achieve concurrency in programming which means different part of the same program can execute parallelly and independently.
Now that we understand what threads are, let now look at goroutines and understand how is it different from threads.

 

How to create Goroutine in Golang with Examples

What is Goroutine ?

Goroutine in Golang is the mechanism to achieve concurrency in programming. It is called as ‘inexpensive’ concurrency thread built into the GO language. They are light weighted and are managed by the GO runtime. Unlike threads, it abstract away memory management and other complexities. Hundreds and thousands of GO routine can run simultaneously with minimal overhead. Since Goroutines are managed by the GO runtime unlike threads where threads are managed by operating system’s thread scheduler, it multiplexes them onto a smaller number of OS threads. We will see how the Goroutines are implemented and how the flow works in the next section.

 

How to Create Goroutine in Golang with Examples

Creating Goroutines in GO is as simple as creating a variable. We just add the word ‘go’ in front of a regular function and that becomes a Goroutine. For example, see below two lines.

fourWheeler()             – Regular function
go fourWheeler()       – Goroutine

Also Read: How To Install Go Extension in VS Code Using 9 Easy Steps

If we add go in front of regular function fourWheeler(), it will be become  Goroutine. Let’s understand it more clearly by an example. We have created a Go code below.

Regular code

package main

import (

    "fmt"
    "time"
)

func main() {

    fourWheeler()         // 1
    twoWheeler()         // 2

    fmt.Println("\nMain function execution is completed")       //3
}

func fourWheeler() {

    time.Sleep(time.Second * 2)
    fmt.Println("\nHi from fourWheeler function")
}

func twoWheeler() {

    time.Sleep(time.Second * 2)
    fmt.Println("\nHi from twoWheeler function")
}

 

OUTPUT
PS C:\Users\linuxnasa\OneDrive\Desktop\Go-Dump> go run .\hello-world.go
Hi from fourWheeler function
Hi from twoWheeler function
Main function execution is completed

 

Let’s understand what above code is doing. We have created two functions, fourWheeler() which will wait for 2 second then prints a message ‘Hi from fourWheeler function’ and twoWheeler() function which will again wait for 2 seconds and prints a message ‘Hi from twoWheeler function’. When you  execute this code, you will notice that execution takes place in below sequential order.

//1 –  fourWheeler() is called and completes it’s job

//2 –  twoWheeler() is called and completes it’s job

//3 –  main function  print statement is executed

Now we will use the same code and convert it in goroutine by adding a keyword ‘go’ in front of both the functions. We will also add a sleep of 4 seconds before main function message is printed. This is required because fourWheer() and twoWheeler() requires 2 seconds each to complete it’s job. Since this is a goroutine, execution of both function will happen concurrently. Hence, main function needs to wait for some seconds before executing it’s print statement. I will suggest you to delete the sleep statement from main function and observe the behavior of execution for better understanding.

 

Goroutine

package main

import (

    "fmt"
    "time"
)

func main() {

    go fourWheeler()             //1
    go twoWheeler()             //1

    time.Sleep(time.Second * 4)                       //2
    fmt.Println("\nMain function execution is completed")
}

func fourWheeler() {

    time.Sleep(time.Second * 2)
    fmt.Println("\nHi from fourWheeler function")
}

func twoWheeler() {
    time.Sleep(time.Second * 2)
    fmt.Println("\nHi from twoWheeler function")
}

 

OUTPUT
PS C:\Users\linuxnasa\OneDrive\Desktop\Go-Dump> go run .\hello-world.go
Hi from fourWheeler function
Hi from twoWheeler function
Main function execution is completed

 

When you will execute above code, you will notice that execution of both the function, fourWheeler() and twoWheeler() takes place parallelly i.e both function will print the message at the same time and then the main function message is printed. Hence, the purpose of using goroutine is achieved i.e tasks are executed concurrently. Below is the execution order.

//1 –   fourWheeler() and twoWheeler() executes concurrently

//2 –  main function print statement is executed

 

Conclusion

In this tutorial, we learnt about how Goroutine is created and how they are different from traditional thread. Goroutine is the mechanism to achieve concurrency in Go. So it is important to get our hands dirty with goroutine in order to master the concurrency.

Leave a Comment