Junior — Middle
Mis teeb goroutine'id traditsiooniliste niitide võrdluses tõhusamaks?
sobes.tech AI
Vastus AI-lt
Goroutines in Go are more efficient than traditional threads due to several key features:
- Lightweight: Goroutines occupy very little memory (usually about 2 KB stack), whereas system threads require much more memory.
- Language-level scheduler: Go has its own goroutine scheduler that efficiently distributes their execution across system threads, allowing thousands of goroutines to run simultaneously without significant overhead.
- Fast creation and context switching: Creating and switching between goroutines is much faster than between OS threads, reducing multitasking costs.
Example of creating a goroutine:
func sayHello() {
fmt.Println("Hello from goroutine")
}
func main() {
go sayHello() // start goroutine
time.Sleep(time.Second) // wait for the goroutine to finish
}