Junior — Middle
How is memory allocation and management carried out when using goroutines in Go?
sobes.tech AI
Answer from AI
In Go, goroutines are lightweight threads managed by the Go runtime. When a goroutine is created, a small stack memory (usually around 2 KB) is allocated, which can grow and shrink dynamically as needed. This allows efficient memory usage, as the stack is not fixed and adapts to the load.
Memory management is handled by the Go scheduler, which distributes goroutines across system threads. The goroutine's stack is located on the heap, and the garbage collector automatically frees unused memory.
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
}
Thus, Go hides the details of goroutine memory management from the developer, ensuring simplicity and efficiency in parallel execution.