Junior — Middle
How is the initialization and execution of a new goroutine performed in a program?
sobes.tech AI
Answer from AI
In Go, a new goroutine is created using the keyword go, followed by a function or method call. This creates a lightweight thread of execution that runs concurrently with the main program.
The initialization and start of a goroutine occur as follows:
gois called before a function:go myFunction().- The Go scheduler creates a new goroutine and puts it in the execution queue.
- The goroutine begins executing asynchronously, independently of the main program.
Example:
func sayHello() {
fmt.Println("Hello from goroutine")
}
func main() {
go sayHello() // start goroutine
fmt.Println("Hello from main")
time.Sleep(time.Second) // give the goroutine time to execute
}
It is important to remember that goroutines are very lightweight compared to OS threads, and their scheduling and switching are managed by the Go runtime, which allows for efficient resource utilization.