Junior — Middle
What processes are launched and how is a new goroutine created in Go?
sobes.tech AI
Answer from AI
In Go, creating a new goroutine is done using the keyword go, followed by a function call. This creates a lightweight thread of execution — a goroutine, which the Go scheduler runs in parallel with others.
The process of creating a goroutine includes:
- Allocating a small stack memory for the goroutine (the stack in Go is dynamic and can grow).
- Registering the goroutine with the Go scheduler.
- The scheduler distributes goroutines across system threads (M) and processors (P).
Example:
func sayHello() {
fmt.Println("Hello from goroutine")
}
func main() {
go sayHello() // starts a new goroutine
time.Sleep(time.Second) // to allow the goroutine to complete
}
Thus, creating a goroutine is a quick and lightweight way to create a parallel execution thread managed by the Go runtime.