1.

What do you understand by goroutine in Golang?

Answer»

A goroutine is nothing but a function in Golang that usually RUNS concurrently or parallelly with other functions. They can be imagined as a lightweight thread that has independent execution and can RUN concurrently with other routines. Goroutines are ENTIRELY managed by Go Runtime. Goroutines help Golang achieve concurrency.

  • In Golang, the main function of the main package is considered the main goroutine. It is the starting point of all other goroutines. These goroutines have the power to start their goroutines. Once the execution of the main goroutine is complete, it means that the program has been completed.
  • We can start a goroutine by just specifying the go keyword before the method call. The method will now be called and run as a goroutine. Consider an example below:
package mainimport ( "fmt" "time")func main() { go sampleRoutine() fmt.Println("Started Main") time.Sleep(1 * time.Second) fmt.Println("Finished Main")}func sampleRoutine() { fmt.Println("Inside Sample Goroutine")}

In this code, we see that the sampleRoutine() function is called by specifying the keyword go before it. When a function is called a goroutine, the call will be returned immediately to the next line of the program STATEMENT which is why “Started Main” WOULD be printed first and the goroutine will be scheduled and run concurrently in the background. The sleep statement ensures that the goroutine is scheduled before the completion of the main goroutine. The output of this code would be:

Started MainInside Sample GoroutineFinished Main


Discussion

No Comment Found