Junior — Middle
What is the role of goroutines in managing asynchrony and parallelism in Go?
sobes.tech AI
Answer from AI
Goroutines in Go are lightweight threads that allow efficient management of asynchronous and parallel execution. They are launched using the keyword go and run within a single process, which significantly saves resources compared to system threads.
Goroutines enable writing asynchronous code that appears sequential, simplifying development. The Go scheduler automatically distributes goroutines across available CPU cores, ensuring parallel execution.
Example of launching a goroutine:
package main
import (
"fmt"
"time"
)
func sayHello() {
fmt.Println("Hello from goroutine")
}
func main() {
go sayHello() // launch goroutine
time.Sleep(time.Second) // wait for the goroutine to finish
}
Thus, goroutines are a key tool for concurrent programming in Go, allowing the creation of scalable and responsive applications.