Sobes.tech
Middle+

How are goroutines structured and how much memory do they occupy in the stack?

sobes.tech AI

Answer from AI

Goroutine — is a lightweight thread of execution managed by the Go runtime environment. Unlike OS threads, goroutines are multiplexed onto a smaller number of OS threads. This provides better scalability.

Key aspects:

  • Scheduler: The Go runtime has its own scheduler (M:N scheduler) that manages goroutines (M) on a limited number of OS threads (N).
  • Memory Manager: Manages goroutine stacks and their growth/shrinkage.
  • Communication: Goroutines interact via channels, ensuring safe data exchange without locks/mutexes in most cases.

Goroutine stack:

  • Initially, goroutine stacks are small, usually 2 KB (before Go 1.4, it was 4 KB).
  • The stack is growing and shrinking. When overflowed, it automatically expands, and when memory is released, it shrinks.
  • This dynamic stack management reduces overhead compared to fixed large OS thread stacks.

Memory occupied in the stack:

  • At creation, a goroutine typically occupies 2 KB of memory for its stack.
  • Memory consumption can dynamically increase during function calls and decrease upon return.
  • The maximum stack size is limited but large enough for most tasks (usually several MB).
package main

import (
	"fmt"
	"runtime"
	"time"
)

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

func main() {
	// Demonstration of creating a goroutine
	go sayHello()

	// To observe goroutine activity
	time.Sleep(100 * time.Millisecond)

	fmt.Printf("Number of goroutines: %d\n", runtime.NumGoroutine())
}

In this example, sayHello runs as a separate goroutine. runtime.NumGoroutine() shows the number of active goroutines (including the main one).