Middle+
How do goroutines differ from OS threads?
sobes.tech AI
Answer from AI
Goroutines in Go are lightweight threads managed by the Go runtime, not the operating system. Key differences:
- Lightweight: Goroutines use much less memory (usually a few kilobytes of stack), whereas OS threads require significantly more resources.
- Scheduling: The Go runtime's scheduler manages goroutines at the user level, allowing efficient switching between goroutines without kernel intervention.
- Scalability: Thousands or even millions of goroutines can run simultaneously, which is practically impossible with OS threads.
- Communication: Goroutines typically communicate via channels, simplifying synchronization and data exchange.
Example of creating a goroutine:
package main
import (
"fmt"
"time"
)
func sayHello() {
fmt.Println("Hello from goroutine")
}
func main() {
go sayHello() // start goroutine
time.Sleep(time.Second) // give the goroutine time to execute
}
Thus, goroutines are an efficient way to perform parallel code execution with low overhead.