Sobes.tech
Junior

How do goroutines differ from threads (threads)?

sobes.tech AI

Answer from AI

Goroutines differ from threads in the following key aspects:

  • Management: Goroutines are managed by the Go runtime, whereas threads are managed by the operating system. This makes switching between goroutines significantly easier and faster, as it does not require a kernel context switch.
  • Costs: Creating and managing goroutines requires much fewer resources (memory and time) compared to threads. A goroutine starts with a very small stack (a few kilobytes), which can grow or shrink dynamically as needed, whereas threads have a fixed, often much larger stack.
  • Scalability: Due to low costs, hundreds of thousands or even millions of goroutines can be easily created in a single application, whereas creating the same number of threads quickly exhausts system resources.
  • Scheduling: The Go scheduler multiplexes a large number of goroutines onto a smaller number of OS threads. This implements cooperative multitasking among goroutines on a single OS thread (though with some preemption), whereas OS threads are managed by the operating system scheduler, which uses preemptive multitasking.
Aspect Goroutines Threads
Management Go runtime Operating system
Costs Low (memory, time) High (memory, time)
Scalability Very high Limited by system resources
Scheduling Go scheduler (cooperative) OS scheduler (preemptive)
Stack Dynamic, small Fixed, often large

Example of creating a goroutine:

package main

import (
	"fmt"
	"time"
)

func task(id int) {
	fmt.Printf("Goroutine %d started\n", id)
	time.Sleep(time.Second)
	fmt.Printf("Goroutine %d finished\n", id)
}

func main() {
	go task(1) // Creating a goroutine
	go task(2) // Creating another goroutine

	time.Sleep(2 * time.Second) // Wait for goroutines to finish
	fmt.Println("Main goroutine finished")
}