Sobes.tech
Junior — Middle

How does the execution of code in a goroutine differ from that of a system thread?

sobes.tech AI

Answer from AI

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

  • Lightweight: Goroutines occupy very little memory (usually a few kilobytes of stack), whereas system threads require much more resources.
  • Scheduling: The Go runtime's scheduler is built-in and distributes goroutines across system threads, allowing efficient CPU utilization.
  • Creation and switching: Creating and switching between goroutines is faster than between system threads, as it does not require kernel context switches.

Example:

func main() {
    go func() {
        fmt.Println("Goroutine")
    }()
    fmt.Println("Main thread")
    time.Sleep(time.Second) // Wait for goroutine to finish
}

Here, the goroutine is launched within the process but does not directly correspond to a separate system thread.

How does the execution of code in a goroutine differ… - sobes.tech