Sobes.tech
Senior

Mis on gorutin? Kuidas see on üles ehitatud?

sobes.tech AI

Vastus AI-lt

A goroutine is a lightweight thread of execution in the Go language. Unlike system threads, goroutines are managed by the Go runtime and have a very small stack (starting with a few kilobytes and can grow dynamically). This allows hundreds of thousands of goroutines to run concurrently with low overhead.

Structure of a goroutine:

  • When creating a goroutine (using the go operator), the Go scheduler places it in the ready queue.
  • The Go runtime uses M:N scheduling: M system threads (OS threads) handle N goroutines.
  • Goroutines switch context at the runtime level, which is faster than switching between system threads.
  • Each thread (M) can execute multiple goroutines (N), switching between them on blocking or as needed.

Example of creating a goroutine:

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

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