×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Go program to demonstrate the multiple Goroutines

Here, we are going to demonstrate the multiple Goroutines in Golang (Go Language).
Submitted by Nidhi, on March 23, 2021 [Last updated : March 04, 2023]

How to implement multiple Goroutines in Golang?

Problem Solution:

In this program, we will create two user-defined functions and call both functions as a goroutine concurrently to print messages on the console screen.

Program/Source Code:

The source code to demonstrate multiple Goroutines is given below. The given program is compiled and executed successfully.

Golang code to implement multiple Goroutines

// Go program to demonstrate multiple Goroutines

package main

import "fmt"
import "time"

func PrintNum() {
	for i := 0; i < 3; i++ {
		time.Sleep(500 * time.Millisecond)
		fmt.Printf("%d\n", i)
	}
}

func ShowMsg(msg string) {
	for i := 0; i < 3; i++ {
		time.Sleep(500 * time.Millisecond)
		fmt.Printf("%s\n", msg)
	}
}

func main() {
	fmt.Println("Start: Main function")
	//Goroutine call
	go ShowMsg("Hello World")

	//Goroutine call
	go PrintNum()

	time.Sleep(3500 * time.Millisecond)
	fmt.Println("End: Main function")
}

Output:

Start: Main function
0
Hello World
1
Hello World
2
Hello World
End: Main function

Explanation:

In the above program, we declare the package main. The main package is used to tell the Go language compiler that the package must be compiled and produced the executable file. Here, we imported the fmt and time packages to use time and fmt related functions.

In the main() function, we created two user-defined functions PrintNum(), ShowMsg(). Then we called both functions as a goroutine concurrently to print messages on the console screen.

Golang Goroutines Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.