Q:

Go program to call a Goroutine with another normal function concurrently

belongs to collection: Golang Goroutines Programs

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

The source code to call a Goroutine with another normal function concurrently is given below. The given program is compiled and executed successfully.

// Go program to call a Goroutine with another
// normal function concurrently

package main

import "fmt"
import "time"

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

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

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

	//normal function call
	PrintNum()
}

Output:

Hello World
0
Hello World
1
Hello World
2
Hello World
3

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 PrintNum() as a normal function and ShowMsg() as a goroutine for concurrent execution.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Go program to create an anonymous Goroutine... >>
<< Go program to demonstrate a simple Goroutine...