×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Go program to create an anonymous Goroutine

Here, we are going to learn how to create an anonymous Goroutine in Golang (Go Language)?
Submitted by Nidhi, on March 23, 2021 [Last updated : March 04, 2023]

Creating an anonymous Goroutine in Golang

Problem Solution:

In this program, we will create an anonymous Goroutine inside the main() function and call anonymous goroutine with the main() function concurrently to print messages on the console screen.

Program/Source Code:

The source code to create an anonymous Goroutine is given below. The given program is compiled and executed successfully.

Golang code to create an anonymous Goroutine

// Go program to create an anonymous Goroutine

package main

import "fmt"
import "time"

func main() {
	fmt.Println("Start: Main function")

	//Simple Anonymous Goroutine
	go func() {
		for i := 0; i < 4; i++ {
			time.Sleep(1 * time.Second)
			fmt.Println("Hello World")
		}
	}()

	for i := 0; i < 4; i++ {
		time.Sleep(1 * time.Second)
		fmt.Println("Hello India")
	}
	fmt.Println("End: Main function")
}

Output:

Start: Main function
Hello World
Hello India
Hello India
Hello World
Hello World
Hello India
Hello India
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 an anonymous Goroutine inside the main() function and called anonymous goroutine with main() function concurrently to print messages on the console screen.

Golang Goroutines Programs »





Comments and Discussions!

Load comments ↻





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