Senior
What is a goroutine and how does it work?
sobes.tech AI
Answer from AI
A goroutine is a lightweight thread of execution in the Go language, managed by the Go runtime rather than the operating system. It allows functions to run concurrently with minimal memory and context switch overhead.
When you call a function with the go keyword, a new goroutine is created, which runs concurrently with others. The Go runtime automatically schedules goroutines across available OS threads.
Example:
package main
import (
"fmt"
"time"
)
func sayHello() {
fmt.Println("Hello from goroutine")
}
func main() {
go sayHello() // starts a goroutine
time.Sleep(time.Second) // wait to let the goroutine finish
}
Goroutines are efficient for implementing concurrent tasks such as request handling, parallel computations, etc.