Sobes.tech
Middle

What is a goroutine and how does it differ from a thread of the operating system?

sobes.tech AI

Answer from AI

A goroutine is a lightweight thread of execution in the Go language, managed by the Go runtime rather than the operating system. Unlike OS threads, goroutines use much less memory (usually a few kilobytes of stack, which can grow dynamically) and are created much faster.

Main differences:

  • Lightweight: thousands of goroutines can run simultaneously, whereas OS threads are heavier and limited in number.
  • Scheduling: goroutines are scheduled by the Go scheduler, which distributes them across system threads, ensuring efficient CPU utilization.
  • Communication: goroutines typically communicate via channels, simplifying synchronization and data exchange.

Example of creating a goroutine:

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

func main() {
    go sayHello() // start goroutine
    time.Sleep(time.Second) // wait for the goroutine to finish
}