Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Last Updated: Mar 27, 2024
Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

Goroutines are a unique feature of the Go programming language. A Goroutine is a function or method that runs in parallel with any other Goroutines in your application, independently and simultaneously. Goroutines, or concurrently performing activities in the Go programming language, are referred to as such. A Goroutine can compare to a lightweight thread.

Create a Goroutine

You can make a Goroutine by simply prefixing the function or method call with the go keyword, as shown in the syntax below:

Syntax

func name(){
// statements
}
// using go keyword as the 
// prefix of your function call
go name()

Example

package main
import (
    "fmt"
    "time"
)
func display(str string) {
    for w := 0; w < 6; w++ {
        time.Sleep(1 * time.Second)
        fmt.Println(str)
    }
}
func main() {
    // Calling Goroutine
    go display("Welcome")
  
    // Calling normal function
    display("CodingNinjas")
}

Output:

Welcome
CodingNinjas
CodingNinjas
Welcome
Welcome
CodingNinjas
CodingNinjas
Welcome
Welcome
CodingNinjas
CodingNinjas

In the above example, we simply build a display() function and then call it in two ways. The first is through a Goroutine.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Fetch Values from Goroutines

Channels are the most logical way to get a value from a goroutine. Channels are pipes that connect goroutines that are running at the same time. You can send values from one goroutine to channels and receive them from another goroutine or the asynchronous function.

Example

package main

import "fmt"

func sum(a, b int, res chan int) {
	temp := a + b
	res <- temp
	return
}

func main() {
	res := make(chan int, 1)
	go sum(2, 3, res)

	sumVal := <-res
	fmt.Printf("Value: %d\n", sumVal)
	close(res)

}

Output

Value: 5

Play and Pause Execution of Goroutine

We can utilize channels to play and pause goroutine execution. A channel facilitates communication between goroutines by acting as a conduit.

Example

package main
import (
"fmt"
"sync"
"time"
)
var i int
func work() {
	time.Sleep(250 * time.Millisecond)
	i++
	fmt.Println(i)
}
func routine(command <-chan string, wg *sync.WaitGroup) {
	defer wg.Done()
	var status = "Play"
	for {
	select {
		case cmd := <-command:
		fmt.Println(cmd)
		switch cmd {
			case "Stop":
				return
			case "Pause":
				status = "Pause"
			default:
			status = "Play"
		}
		default:
			if status == "Play" {
				work()
			}
		}
	}
}
func main() {
	var wg sync.WaitGroup
	wg.Add(1)
	command := make(chan string)
	go routine(command, &wg)

	time.Sleep(1 * time.Second)
	command <- "Pause"

	time.Sleep(1 * time.Second)
	command <- "Play"

	time.Sleep(1 * time.Second)
	command <- "Stop"

	wg.Wait()
}

Output

1
2
3
4
Pause
Play
5
6
7
8
Stop

Advantages of Goroutines

  • Goroutines are cheaper than threads.
  • Goroutine is placed in a stack, which can expand and shrink in size depending on the program's requirements. Threads, on the other hand, have a set stack size.
  • Goroutines can interact through the channel, which is specifically designed to prevent race situations when Goroutines access shared memory.
  • Assume a software has a single thread with several Goroutines associated with it. If any Goroutine blocks the thread owing to resource constraints, the remaining Goroutines will be assigned to a new OS thread. The programmers are unaware of all of this information.

FAQs

  1. What is the use of Add, Done, Wait for Waiting for Goroutines to Finish Execution? 
    Ans: To add a counter to the WaitGroup, use the Add method. To decrement the WaitGroup counter, the Done method of WaitGroup is scheduled using a defer statement. The Wait way of the WaitGroup type waits for all goroutines in the program to complete.
     
  2. Why Define Critical Sections using Mutex? 
    Ans: A mutex is used to establish a crucial area around code, ensuring that only one goroutine can execute that code portion at a time.

Key Takeaways

In this article, we have extensively discussed Routines and learned the syntax and implementation by example, and also learned play and pause execution.

We hope that this blog enhances your knowledge regarding Routines, and if you would like to learn more, check out all articles on Concurrency in GoInterview Preparation. Do upvote our blog to help other ninjas grow. Happy Coding!

Topics covered
1.
Introduction
2.
Create a Goroutine
2.1.
Syntax
2.2.
Example
3.
Fetch Values from Goroutines
3.1.
Example
4.
Play and Pause Execution of Goroutine
4.1.
Example
5.
Advantages of Goroutines
6.
FAQs
7.
Key Takeaways