What is a Goroutine?


A goroutine is a lightweight thread of execution in the Go programming language. It is similar to a thread in other programming languages, but it is managed by the Go runtime rather than the operating system. Goroutines allow concurrent execution of functions in a program, and they are designed to be efficient and scalable.

In Go, a program starts with a single goroutine, which executes the main function. Additional goroutines can be created using the go keyword followed by a function call. This starts a new goroutine that runs concurrently with the original goroutine.

Goroutines are very lightweight, and it's possible to create thousands or even millions of them in a single program without significant overhead. This makes it easy to write concurrent programs in Go that take advantage of multiple CPU cores and can perform many tasks simultaneously.

Because goroutines are managed by the Go runtime, they are automatically scheduled and can communicate with each other using channels. This makes it easy to write complex concurrent programs without worrying about low-level details such as locking and synchronization.

Goroutines communicate with each other using channels, which are a built-in feature of the Go language. Channels provide a way for goroutines to send and receive values to and from each other, and they are used to synchronize access to shared data.

Goroutines are a key feature of the Go language, and they are used extensively in the design of concurrent and parallel programs. They make it easy to write code that is both efficient and easy to reason about.

New goroutines are created by the go statement.

To run a function as a goroutine, call that function prefixed with the go statement. Here is the example code block:

Example

sum()     // A normal function call that executes sum synchronously and waits for completing it
go sum()  // A goroutine that executes sum asynchronously and doesn't wait for completing it

The go keyword makes the function call to return immediately, while the function starts running in the background as a goroutine and the rest of the program continues its execution. The main function of every Golang program is started using a goroutine, so every Golang program runs at least one goroutine.

Most Helpful This Week