Senior
What is a goroutine? How is it structured?
sobes.tech AI
Answer from AI
A goroutine is a lightweight thread of execution in the Go language. Unlike system threads, goroutines are managed by the Go runtime and have a very small stack (starting from a few kilobytes and can grow dynamically). This allows hundreds of thousands of goroutines to run concurrently with low overhead.
Goroutine structure:
- When creating a goroutine (using the
gooperator), the Go scheduler places it in a queue of ready-to-run tasks. - The Go runtime uses M:N scheduling: M system threads (OS threads) serve N goroutines.
- Goroutines switch at the runtime level, which is faster than switching system threads.
- Each thread (M) can execute multiple goroutines (N), switching between them when blocked or as needed.
Example of creating a goroutine:
func sayHello() {
fmt.Println("Hello from goroutine")
}
func main() {
go sayHello() // start a goroutine
time.Sleep(time.Second) // wait for the goroutine to finish
}