Golang Working with goroutine

Golang Working with goroutine

Note: To execute golang code online you can use https://play.golang.org/

What is goroutine ?

  • Goroutines are functions or methods that run concurrently with other functions or methods.
  • Goroutines can be thought of as lightweight threads.
  • The cost of creating a Goroutine is tiny when compared to a thread.

The benefits of Goroutines

  • They are lightweight.
  • Ability to scale seamlessly.
  • They are virtual threads.
  • Less memory requirement (2KB).
  • Provide additional memory to Goroutines during runtime.

how to implement goroutine?

  • we need use the keyword go before the function call. let's see an example.

package main

import (  
    "fmt"
)

func callme() {  
    fmt.Println("goroutine called")
}
func main() {  
    go callme()
    fmt.Println("main function")
}
- When we run above code we can see that the goroutine code didn't get executed. - After, the first statement go callme() the main control goes to the next line fmt.Println("main function") and then exits. - So, the go routine didn't have enough time to execute it. Hence, it didn't executed.

package main

import (  
    "fmt"
    "time"
)

func callme() {  
    fmt.Println("goroutine called")
}
func main() {  
    go callme()
    time.Sleep(1 * time.Second)
    fmt.Println("main function")
}
  • If we execute the above code we can see that the goroutine executes callme function code.
  • Because, we are keeping the seep mode time.Sleep(1 * time.Second) in the program which gives the goroutine enough time to execute.

References

  1. https://golangbot.com/goroutines/