Junior — Middle
Kuidas toimub mälu eraldamine ja haldamine Go keeles goroutine'ide kasutamisel?
sobes.tech AI
Vastus AI-lt
In Go, goroutines are lightweight threads managed by the Go runtime. When creating a goroutine, 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 the goroutine
time.Sleep(time.Second) // wait for the goroutine to complete
}
Thus, Go hides the details of goroutine memory management from the developer, ensuring simplicity and efficiency in parallel execution.