Junior — Middle
What are the advantages of using goroutines compared to system threads for improving application performance?
sobes.tech AI
Answer from AI
Goroutines in Go have several advantages over system threads:
- Lightweight: Goroutines consume much less memory (usually a few kilobytes), whereas system threads require significantly more resources.
- Scalability: Thousands or even millions of goroutines can be run simultaneously, which is difficult with threads.
- Fast context switching: The Go scheduler efficiently manages goroutines, switching between them faster than the OS switches between threads.
- Simplified synchronization: Built-in channels and other primitives simplify data exchange between goroutines.
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) // wait for the goroutine to finish
}