×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Go program to demonstrate a simple Goroutine

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

How to implement a simple Goroutine in Golang?

Problem Solution:

In this program, we will create a user-defined function. Here, we will call a function as a goroutine using the "go" keyword. A goroutine is used to execute concurrent program execution.

Program/Source Code:

The source code to demonstrate a simple Goroutine is given below. The given program is compiled and executed successfully.

Golang code to implement a simple Goroutine

// Go program to demonstrate a simple Goroutine.

package main

import "fmt"
import "time"

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

func main() {
	//Goroutine call
	go ShowMsg("Hello World")

	//normal function call
	ShowMsg("Hello India")
}

Output:


Hello India
Hello World
Hello India
Hello World
Hello India
Hello World
Hello India

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 a user-defined function ShowMsg() to print specified message. Here, we called ShowMsg() function as a goroutine using the "go" keyword and normal function without using the "go" keyword. The go-routine is used for concurrent execution.

Golang Goroutines Programs »





Comments and Discussions!

Load comments ↻





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