Sobes.tech
Middle+

What are goroutines, and how are they structured internally?

sobes.tech AI

Answer from AI

Goroutines are lightweight execution threads in Go, managed by the language runtime rather than the operating system. Unlike system threads, goroutines have very small stacks (starting from a few kilobytes) and can grow dynamically.

Inside a goroutine, there is a g (goroutine) structure that contains its state, stack, registers, and other information. The Go scheduler manages switching between goroutines using an M:N model, where M is the number of system threads (OS threads), and N is the number of goroutines.

The scheduler distributes goroutines across system threads, allowing efficient utilization of multi-core processors without the overhead of creating and switching OS threads. This is achieved through cooperative and preemptive multitasking within the runtime.

Example of creating a goroutine:

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

func main() {
    go sayHello() // start goroutine
    time.Sleep(time.Second) // give the goroutine time to execute
}
What are goroutines, and how are they structured… - sobes.tech