Sobes.tech
Middle

What is a goroutine in the context of Go?

sobes.tech AI

Answer from AI

A goroutine is a lightweight thread of execution in the Go language. It is started using the go keyword and runs concurrently with other goroutines within the same process. Unlike system threads, goroutines have a small stack (usually a few kilobytes) that dynamically expands, allowing thousands or even millions of goroutines to run simultaneously with minimal resource consumption.

Example of creating a goroutine:

func sayHello() {
    fmt.Println("Hello from goroutine")
}

func main() {
    go sayHello() // start a goroutine
    time.Sleep(time.Second) // give the goroutine time to execute
}

Goroutines communicate via channels, which simplifies synchronization and data exchange between them.