Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

golang
goroutines
communitycreator

How to use goroutines in golang

Jeyabalaji Subramanian

Goroutines are functions or methods that run concurrently with other functions or methods. Goroutines can be thought of as lightweight threads. The cost of creating a Goroutine is tiny when compared to a thread. As a result, you can easily compose robust concurrent programs in Golang with ease.

A simple Goroutine in action

Let’s look at this simple hello world function in Golang and invoke it as a Goroutine.

package main

import (
	"fmt"
)

func hello() {
	fmt.Println("hello from a goroutine!")
}

func main() {
	go hello()
}

What did you observe when you ran the code? Did you see the print statement? You would not have! Why?

A Go program doesn’t wait for your goroutines to finish.

So, how do you make the “main” thread wait for the Goroutines to complete? Take a look at this shot to learn how.

RELATED TAGS

golang
goroutines
communitycreator

CONTRIBUTOR

Jeyabalaji Subramanian
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring