Sobes.tech
Senior

Goroutines — what are they, and why are they more efficient than OS processes?

sobes.tech AI

Answer from AI

Goroutines are lightweight execution threads in the Go language, managed by the Go runtime rather than the operating system. They allow functions to run concurrently with minimal overhead for creation and context switching.

Why are they more efficient than OS processes:

  • Small stack size: a goroutine starts with a small stack (about 2 KB), which can grow dynamically, unlike OS threads with a fixed large stack.
  • Fast context switching: switching between goroutines occurs in user space, without kernel involvement, which is much faster.
  • Scalability: thousands or even millions of goroutines can run simultaneously, which is not possible with OS threads due to resource limitations.

Example of creating a goroutine in Go:

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

func main() {
    go sayHello() // starts a goroutine
    time.Sleep(time.Second) // waits for the goroutine to finish
}
Goroutines — what are they, and why are they more… - sobes.tech