Middle+
Why were goroutines invented, if there are OS threads?
sobes.tech AI
Answer from AI
Goroutines in Go were designed for easier and more efficient handling of concurrency compared to OS threads. The main advantages of goroutines:
- Lightweight: Goroutines consume much less memory than OS threads, and thousands or even millions can be created without significant resource consumption.
- Language-level scheduler: Go has a built-in scheduler that efficiently distributes goroutines across OS threads, optimizing CPU usage.
- Simple syntax: Starting a goroutine is as simple as adding the
gokeyword before a function call.
Example of creating a goroutine:
func sayHello() {
fmt.Println("Hello from goroutine")
}
func main() {
go sayHello() // runs the function in a goroutine
time.Sleep(time.Second) // gives the goroutine time to execute
}
Thus, goroutines allow writing concurrent code more simply and efficiently than managing OS threads directly.