Middle
What are goroutines in Go and how do they differ from system threads?
sobes.tech AI
Answer from AI
Goroutines in Go are lightweight threads managed by the Go runtime, not the operating system. They allow functions to run concurrently with minimal memory and context switch overhead.
Differences from system threads:
- Goroutines are much lighter in resources (usually start with a few kilobytes of stack, which grows dynamically).
- The scheduler for goroutines is built into the Go runtime and efficiently distributes them across system threads.
- Switching between goroutines is faster than between system threads.
Example of creating a goroutine:
func sayHello() {
fmt.Println("Hello from goroutine")
}
func main() {
go sayHello() // starts a goroutine
time.Sleep(time.Second) // wait for the goroutine to finish
}