Sobes.tech
Middle

What is the difference between a goroutine and an operating system thread?

sobes.tech AI

Answer from AI

Goroutines are lightweight threads managed by the Go runtime, not the operating system. Key differences:

  • Lightweight: Goroutines occupy very little memory (usually a few kilobytes of stack), unlike OS threads which require much more resources.
  • Scheduling: The Go runtime's scheduler manages goroutines and can switch between them much faster than the OS switches threads.
  • Scalability: Thousands or even millions of goroutines can run simultaneously, which is practically impossible with OS threads.
  • Concurrency model: Goroutines typically use channels and other Go primitives for synchronization, simplifying concurrent programming.

Example of creating a goroutine:

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

Unlike OS threads, there's no need to explicitly create and manage threads — this is handled by the Go runtime.