Sobes.tech
Senior

What is a goroutine? What makes it lightweight?

sobes.tech AI

Answer from AI

A goroutine is a lightweight thread of execution in the Go language. Unlike system threads, goroutines are managed by the Go runtime and have a very small initial stack (usually around 2 KB), which can grow dynamically. This allows thousands or even millions of goroutines to run concurrently with low memory overhead and context switching costs.

The lightweight nature of goroutines is achieved through:

  • A small initial stack size that grows and shrinks as needed.
  • Management by the Go scheduler, which efficiently distributes goroutines across system threads.
  • The absence of the need to create separate system threads for each goroutine.

Example of creating a goroutine:

package main
import (
    "fmt"
    "time"
)

func sayHello() {
    fmt.Println("Hello from goroutine")
}

func main() {
    go sayHello() // start a goroutine
    time.Sleep(time.Second) // give the goroutine time to execute
}

Thus, goroutines enable efficient concurrency and parallelism in Go.

What is a goroutine? What makes it lightweight… - sobes.tech